bash loop through parameters

for i in $*
do
#will echo all the variable passes as parameters
echo $i
done

Comments

neo2k said…
Thanks mate, was playing around with some bash scripting for some simple cron jobs.
Anonymous said…
That doesn't work:

$ touch 'foo bar'
$ ./test foo*
foo
bar
$

If you're that incompetent and can't even bother to test your own advice then why do you bother giving advice at all? Just to piss people off?
Ben said…
It works just fine. I just verified it.

Don't know what you are smoking bro.
Anonymous said…
Ben, if you're so stupid that you're unable to perform even a simple test like that then maybe you should shut up. The script most certainly does NOT work.

$ cat test1.sh
for i in $*
do
echo $i
done
$ ./test1.sh 'foo bar'
foo
bar
$

See? The script shows it as 2 parameters, "foo" and "bar", although there is only one, "foo bar".

OTOH, here is a version that DOES work:

$ cat test2.sh
while [ $# -ne 0 ]; do
echo "$1"
shift
done
$ ./test2.sh 'foo bar'
foo bar
$
Unknown said…
That way has a bug!

$ ./test a\ b c

Will be parsed as three arguments by that for loop, when in reality it is two arguments (with an escaped space in the first argument.)

The while loop is the way to go.
Ron Frazier said…
This works, too:

for i in "$@"
do
echo "$i"
done
jasonofcompsci said…
I was wondering how one would get rid of argument $0. So it would be $1 -> $n.
Maybe boolean above it to switch to eating the first arg.

for i in $*
do
if(DO)
then
echo $i
fi
D0=1
done

I'm not a bash-scripter by the way.
msutherl said…
@jasonofcompsci before your for loop, you can:

shift n

to shift the positional parameters to the left
Anonymous said…
Easier:

for a
do
echo $a
done

This will loop all arguments except $0
Twinky said…
This comment has been removed by the author.
Twinky said…
This way uses indirect variables to loop through all of the true arguments. (a.k.a. "testo mesto" is one argument)

for (( i=1; i<=$#; i++ )); do
eval arg=\$$i
echo "Hello $arg"
done

Popular posts from this blog

Vim vi how to reload a file your editing