views:

29

answers:

3

Hi,

I want to pass many arguments to a shell script which I don't know how many arguments they are going to be and I want to handle them. I did the following code:

int=$1
src=$2

r=$3
string=$4

duration=$5

./start.sh $int $r $src "$string"
sleep $duration

shift; shift; shift; shift; shift

while [ $# -gt 2 ]
do
  r=$1
  string=$2
  duration=$3
  ./change.sh $int $r "$string"
  sleep $duration
  shift; shift; shift
done

That works but only for one time, now I want this script to run all the time, I mean using while 1 but that won't work this way because the argument list is empty at the end of that code!

Is there any way to do something like the following "pseudo code" in shell scripts:

for( i=0 ; i<arguments.count; i++ ){
   //do something with arguments[i]
}

or copying the arguments array into another array so that I can use it later the way I want. I mean can I copy $* or $@ or arg into another array?

Any help is highly appreciated.

A: 

You can use $# to get the number of arguments passed to the script, or $@ to get the whole argument list.

Julien Lebosquain
+2  A: 

The number of arguments is stored in the parameter #, which can be accessed with $#.

A simple loop over all arguments can be written as follows:

for arg
do
    # do something with the argument "arg"
done
Philipp
can I use something like `$arg[i]` ?
Reem
Yes, `"${arg[$i]}"` (note the quotes and the braces).
Philipp
`i=1; echo "${arg[$i]}"` printed nothing :(
Reem
`arg` must be an array for this to work. What is `arg` in your code? Note that in my code `arg` is simply a scalar string that cannot be indexed.
Philipp
I tried `for arg; do; echo $arg; done` and I got all the arguments printed each one at a line.Now I did the same loop and copied the whole arg into another array and I'm using it just like any other array and index it.
Reem
You don't have to copy it, you can use the builtin `ARGV` array.
Philipp
A: 
declare -a array_list
index=0
for arg
do
   array_list[$index]=$arg
   echo ${array_list[$index]} #just to make sure it is copied :)
   ((index++))
done

now I'm using array_list to do whatever I want with the argument list. Thanks

Reem