Loop over the arguments array, without knowing how

2019-07-31 08:48发布

问题:

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.

回答1:

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


回答2:

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



回答3:

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