how to loop through arguments in a bash script
There's a special syntax for this:
for i do
printf '%s\n' "$i"
done
More generally, the list of parameters of the current script or function is available through the special variable $@
.
for i in "$@"; do
printf '%s\n' "$i"
done
Note that you need the double quotes around $@
, otherwise the parameters undergo wildcard expansion and field splitting. "$@"
is magic: despite the double quotes, it expands into as many fields as there are parameters.
print_arguments () {
for i in "$@"; do printf '%s\n' "$i"; done
}
print_arguments 'hello world' '*' 'special !\characters' '-n' # prints 4 lines
print_arguments '' # prints one empty line
print_arguments # prints nothing
#! /usr/bin/env bash
for f in "$@"; do
echo "$f"
done
You should quote $@
because it is possible for arguments to contain spaces (or newlines, etc.) if you quote them, or escape them with a \
. For example:
./myscript one 'two three'
That's two arguments rather than three, due to the quotes. If you don't quote $@
, those arguments will be broken up within the script.