How to iterate over arguments in a Bash script

后端 未结 8 2602
长发绾君心
长发绾君心 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:23

    Note that Robert's answer is correct, and it works in sh as well. You can (portably) simplify it even further:

    for i in "$@"
    

    is equivalent to:

    for i
    

    I.e., you don't need anything!

    Testing ($ is command prompt):

    $ set a b "spaces here" d
    $ for i; do echo "$i"; done
    a
    b
    spaces here
    d
    $ for i in "$@"; do echo "$i"; done
    a
    b
    spaces here
    d
    

    I first read about this in Unix Programming Environment by Kernighan and Pike.

    In bash, help for documents this:

    for NAME [in WORDS ... ;] do COMMANDS; done

    If 'in WORDS ...;' is not present, then 'in "$@"' is assumed.

提交回复
热议问题