3

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
user1470511
  • 339
  • 1
  • 3
  • 14

1 Answers1

7

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[@]}"…
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • So if I wanted to do a specific function call and the second argument being passed in was the list how would you propose iterating through the files? An argument iterator starting at the second one? – user1470511 Jul 23 '12 at 20:50
  • Ok, so I just used a shift with your code and it seemed to work fine. I appreciate the help! – user1470511 Jul 23 '12 at 20:52
  • @user1470511 Assuming you mean the 2nd through the last argument are the list of files, you can use `shift` after assigning the first argument to a name: `first_arg="$1"; shift;`. After this, `"$@"` will consist of your list of arguments. – kojiro Jul 23 '12 at 20:53