【问题标题】:Passing a group of words as a bash script argument将一组单词作为 bash 脚本参数传递
【发布时间】:2017-05-15 07:36:44
【问题描述】:

我想将一组单词作为参数传递给 bash 脚本。好像我想打印参数的时候,只有组的第一个字在打印。

这些是我的脚本,第一个只是将一组单词分配给一个变量并将该变量传递给另一个脚本。第二个只是打印它传递的变量。

脚本.sh

#!/bin/bash
GC='lblue, lblue, lgrey, lred, lred'
./script2.sh $GC

script2.sh

#!/bin/bash
printf "$1 \n"

这是我运行脚本时的当前结果

./script.sh 
lblue, 

我希望脚本改为输出这个

lblue, lblue, lgrey, lred, lred

【问题讨论】:

    标签: bash arguments


    【解决方案1】:

    用双引号将变量括起来以保留空格 - 这是 bash 中的最佳实践之一:

    #!/bin/bash
    GC='lblue, lblue, lgrey, lred, lred'
    ./script2.sh "$GC"
    

    在 script2.sh 中:

    #!/bin/bash
    printf "$1 \n" => when $GC was passed without double quotes, shell treated them as separate words and $1 was the first word
    

    【讨论】:

      【解决方案2】:

      你也可以传递数组:

      script.sh

      #!/bin/bash
      a=("$@")
      gc=$(IFS=, ; printf "${a[*]}"| sed 's/, */, /g' )
      printf "${gc[*]} \n"
      

      输入

      gc=(red green blue)
      ./script.sh ${gc[*]}
      

      输出将是:

      red, green, blue
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-26
        • 2023-04-03
        • 1970-01-01
        • 2020-03-24
        • 1970-01-01
        • 2013-06-18
        • 2013-10-15
        相关资源
        最近更新 更多