开发者

Loop over the arguments array, without knowing how many arguments, in a shell script?

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:

i开发者_JS百科nt=$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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜