How to iterate over arguments in a Bash script

后端 未结 8 2685
长发绾君心
长发绾君心 2020-11-22 02:27

I have a complex command that I\'d like to make a shell/bash script of. I can write it in terms of $1 easily:

foo $1 args -o $1.ext
         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 03:10

    Amplifying on baz's answer, if you need to enumerate the argument list with an index (such as to search for a specific word), you can do this without copying the list or mutating it.

    Say you want to split an argument list at a double-dash ("--") and pass the arguments before the dashes to one command, and the arguments after the dashes to another:

     toolwrapper() {
       for i in $(seq 1 $#); do
         [[ "${!i}" == "--" ]] && break
       done || return $? # returns error status if we don't "break"
    
       echo "dashes at $i"
       echo "Before dashes: ${@:1:i-1}"
       echo "After dashes: ${@:i+1:$#}"
     }
    

    Results should look like this:

     $ toolwrapper args for first tool -- and these are for the second
     dashes at 5
     Before dashes: args for first tool
     After dashes: and these are for the second
    

提交回复
热议问题