Reputation: 349
This could be a simple answer, but after Googling around I might just have the terminology down so I have yet to find anything about what I am asking.
When accepting an argument such as /bin/*.txt how do you iterate through each of the files?
I have tried this:
for file in $2; do
echo $file
done
The second argument ($2) has an input such as the /bin/*.txt but the echo only prints out 1 of the text files out of the 6 I have. Am I iterating through this incorrectly?
I have also tried using ls as such and it will not print out correctly either...
ls $2
Upvotes: 3
Views: 926
Reputation: 77059
Unless the argument is quoted, the argument /bin/*.txt
will be expanded before your script ever sees it. Thus, if the argument is still /bin/*.txt
, you can be sure there are no files matching that glob. Otherwise, you'll have multiple arguments matching all the files that do match, and you can just use the arguments:
for file; do # equivalent to for file in "$@"
echo "$file"
done
If you want the argument to be quoted, you'll have to expand it yourself. An array is a decent way to do this:
arg='/bin/*.txt'
files=( $arg )
for file in "${files[@]}"…
Upvotes: 7