In addition:
Code:
FileList=`find . -name \*$extn`
Single, scalar variables should not be used to store
lists of things like filenames. That's what
arrays are there for.
For trivial, single directory level matches, you can use simple
globbing.
Code:
FileList=( *."$extn" )
Bash v4+ also has a new "
**"
globstar feature that lets you work recursively.
Code:
shopt -s globstar
FileList=( **/*."$extn" )
Note though that I've found it to still have major problems when working on certain directories, particularly my
$HOME.
For more complex matches, including recursive matching, you can use
find, but you need to be careful to do it in a way that handles unusual filenames correctly. This generally involves the
-print0 option.
Code:
while IFS='' read -r -d '' ; do
FileList+=( "$REPLY" )
done < <( find . -name "*.$extn" -print0 )
See these three links for more on filename reading in
bash:
http://mywiki.wooledge.org/BashFAQ/001
http://mywiki.wooledge.org/BashFAQ/020
http://mywiki.wooledge.org/UsingFind
And to use the array, call it using the "
@" symbol, with the whole thing in double-quotes. This ensures that each entry will be expanded as a separate string.
Code:
printf '%s\n' "${FileList[@]}"
n=1
for file in "${FileList[@]}"; do
echo "File $(( n++ )) is: $file"
done
n=1
for index in "${!FileList[@]}"; do #to loop by index number
echo "File $(( n++ )) is: ${FileList[index]}"
done
BTW:
$(..) is highly recommended over `..`