2

如何正确地对$@进行赋值

 3 years ago
source link: https://www.lujun9972.win/blog/2017/01/01/%E5%A6%82%E4%BD%95%E6%AD%A3%E7%A1%AE%E5%9C%B0%E5%AF%B9$@%E8%BF%9B%E8%A1%8C%E8%B5%8B%E5%80%BC/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何正确地对$@进行赋值

$@ 比较特殊,跟一般的 $VAR 都不一样. 当进行赋值时通常需要把 $@ 赋值给数组变量,否则在处理由引号括起来的带空格的参数时就可能会有问题了.

下面是举几个例子作为演示:

  1. 遍历 "$@" 的效果:

    function test
    {
        for var in "$@";do
            echo $var
        done
    }
    
    test 1 "2 3" 4
    
  2. 用一般变量commands保存 "$@",并遍历 "$commands"

    function test
    {
        commands="$@"
        for var in "$commands";do
            echo $var
        done
    }
    
    test 1 "2 3" 4
    

    发现所有参数都合并成一行 1 2 3 4

  3. 用一般变量commands保存 "$@",并遍历 $commands

    function test
    {
        commands="$@"
        for var in $commands;do
            echo $var
        done
    }
    
    test 1 "2 3" 4
    

    发现只输出中把参数 2 3 e拆分开了.

  4. 用数组变量commands保存 "$@",并遍历 "$commands"

    function test
    {
        commands=("$@")
        for var in "${commands[@]}";do
            echo $var
        done
    }
    
    test 1 "2 3" 4
    

    这次的结果总算是正确的了.

总结起来,要正确地对 $@ 进行赋值要注意以下几点:

  1. 使用数组变量保存 $@ 的值:

    commands=("$@")
    
  2. 便利数组变量时,需要使用带引号的@进行遍历

    for var in "${commands[@]}";do
    done
    

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK