Unix "$@" 作为参数

wel*_*lly 0 unix bash

说我有一些命令:

somecommand "$@"
Run Code Online (Sandbox Code Playgroud)

$@ 的意义是什么?这一定是一些我不熟悉的 unix 技巧。不幸的是,因为它都是标点符号,我也不能用谷歌搜索。

Dan*_*eck 5

它是当前的 shell 脚本或函数的参数,单独引用。

man bash 说:

@ 扩展到位置参数,从 1 开始。当扩展发生在双引号内时,每个参数都扩展为一个单独的词。也就是说,"$@"等价于"$1" "$2" ...


鉴于以下脚本:

#!/usr/bin/env bash

function all_args {
    # repeat until there are no more arguments
    while [ $# -gt 0 ] ; do
        # print first argument to the function
        echo $1
        # remove first argument, shifting the others 1 position to the left
        shift
    done
}

echo "Quoted:"
all_args "$@"
echo "Unquoted:"
all_args $@
Run Code Online (Sandbox Code Playgroud)

执行时会发生这种情况:

$ ./demo.sh foo bar "baz qux"
Quoted:
foo
bar
baz qux
Unquoted:
foo
bar
baz
qux
Run Code Online (Sandbox Code Playgroud)