Accessing bash command line args $@ vs $*

后端 未结 5 1884
孤城傲影
孤城傲影 2020-11-22 13:54

In many SO questions and bash tutorials I see that I can access command line args in bash scripts in two ways:

$ ~ >cat testargs.sh 
#!/bin/bash

echo \"y         


        
5条回答
  •  忘了有多久
    2020-11-22 14:03

    The difference appears when the special parameters are quoted. Let me illustrate the differences:

    $ set -- "arg  1" "arg  2" "arg  3"
    
    $ for word in $*; do echo "$word"; done
    arg
    1
    arg
    2
    arg
    3
    
    $ for word in $@; do echo "$word"; done
    arg
    1
    arg
    2
    arg
    3
    
    $ for word in "$*"; do echo "$word"; done
    arg  1 arg  2 arg  3
    
    $ for word in "$@"; do echo "$word"; done
    arg  1
    arg  2
    arg  3
    

    one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

    $ for word in "$@"; do echo $word; done
    arg 1
    arg 2
    arg 3
    

    and in bash, "$@" is the "default" list to iterate over:

    $ for word; do echo "$word"; done
    arg  1
    arg  2
    arg  3
    

提交回复
热议问题