I would like to iterate over the arguments given to a bash script, for example:
./bash_script file1 file2 file3
$@ gives me all the files given to the script but how do I iterate over the files?
I would like to cat each file and remove the contents using awk (I know how to do that, it's the unpacking of $@ that's got me confused).
The trick is to double quote it as in
"$@".is equivalent to:
If the
$@in the above is not double-quoted, then you'll get:due to word splitting on
$IFScharacters ($IFSdefaults to' '$'\t'$'\n', i.e. a space, a tab, and a newline )$@ vs. $*
Double quotes work like this for any @-expansion on any array:
In contrast, *-expansions (e.g.,
$*,${foo[*]}) will use the first character of$IFSto join the items of an array into a single string:which, if left unquoted, will again split on this very IFS character:
Trick for iterating over $@ in for-loops:
The
"$@"array is special. If you want to iterate over"$@"in a for loop, then you can abbreviateas
as skipping the
in somethingpart of aforloop impliesin "$@".This works even in POSIX-only shells too (dash, bourne shell) which don't have array variables but support
"$@"and"$*.