Simple bash array question
Have found myself in the position of needing to write short simple bash script to create an array of directories.
Code:
#! /bin/bash /run/media/david/External_Drive_1 /run/media/david/Misc-Files on seperate lines as expected. What I need to do, (and have not been able to figure out) is to have echo $i return the directory names only, on seperate lines. External_Drive_1 Misc-Files Done my searching, but when I get far into the land of nested brackets and single vs double quotes I am wandering in the dark without a lantern. TIA for any suggestions |
'echo "${i//*\//}";' or 'echo "$(basename "$i")";'
|
Thanks... If you have a moment can you explain ${i//*\//} for my further edification? I almost get why it works, but so simple (like the jitterbug) it has plumb evaded me.
Tks again |
The ${i//*\//} first takes the value of i, the first double forward slash says relplace matching strings with another string. The *\/ is the string to match, the * matches any value, the \/ escapes to a literal /, so the string matches anything up to and including the last /. Everything after the last / is the string to replace, in this case it's blank. So the command finds anything that matches */ (that is anything and up to including the final slash) and replaces it with nothing.
|
Thanks for the explanation ... It becomes clear
|
And one more:
Code:
echo "${i##*/}" |
{ Edit: :doh: I think I mis-read the whole thing. Simple parameter substitution is indeed all that's needed to strip off the pathname of a file. I'll leave this up for posterity anyway. }
If you want to print only the directory names, all you need is one quick fix: Code:
#!/bin/bash "*" outputs all entries, but "*/" only expands directories. Note also though that hidden directories are not expanded by default. You have to add shopt -s dotglob first to get those. You can replace the above loop with a simple printf, by the way. Code:
printf '%s\n' "${drives[@]}" Code:
drives=( /run/media/david/* ) |
thanks again for all the input and suggestions.
|
All times are GMT -5. The time now is 01:36 AM. |