$1
is simply the first parameter passed to your shell script. So if you have a script myscript
and I call it like this:
myscript somefile
Then $1
will be somefile
. If I call it like this:
myscript *
And there happen to be files in my current directory named:
foo bar baz
Then $1
will be foo
. In either case, $1
only has a single value and there is nothing to loop over.
There are a couple of ways to loop over the arguments. The most common is:
for file in "$@"; do
echo doing something with "$file"
done
Note that $@
is not the same as "$@"
; the latter is a special construct that will correctly deal with filenames that contain spaces. You could also do something like:
while [ -n "$1" ]; do
echo doing something with "$1"
shift
done
Here, the shift
command drops the first parameter, and $2
becomes $1
(and so on). This will loop as long as $1
is non-empty. You could also use $#
for this (a variable which contains the number of command line arguments):
while [ $# -gt 0 ]; do
echo arg: "$1"
shift
done
for file in $1
inside the code... to ensure, shell doesn't expand*
, put that argument inside single quotes