Jan
Jan

Reputation: 3

Argument passing in a bash script

I've got following bash script to do something for each parameter of the script

#! /bin/sh

while (($#)); do
 echo $1
 shift
done

But somehow, if I start it with the command sudo ./test.sh foo1 foo2 it wont work. And the real strange thing is, that if I enter sudo bash test.sh foo1 foo2 it works. Does anybody know what causes this strange behaviour?

Upvotes: 0

Views: 254

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360153

This will work in either sh or bash:

for arg
do
    echo "$arg"
done

and it does the same thing as your script is intended to do without destroying the argument list.

Upvotes: 1

jordanm
jordanm

Reputation: 34964

You have specified /bin/sh as your interpreter, which may not be bash. Even if it is bash, bash runs in POSIX mode when called as /bin/sh.

The (( )) command is a bash-specific feature. The following will work in any POSIX compliant shell:

while [ $# -gt 0 ]; do
   echo $1
   shift
done

Upvotes: 3

Terrance Medina
Terrance Medina

Reputation: 23

Have you tried #!/bin/bash rather than sh?

Here's a link explaining the difference: http://www.linuxquestions.org/questions/programming-9/difference-between-bin-bash-and-bin-sh-693231/

Upvotes: 2

Related Questions