代码之家  ›  专栏  ›  技术社区  ›  Mark Biek

喜欢将bash脚本的所有命令行参数存储到单个变量中

  •  13
  • Mark Biek  · 技术社区  · 17 年前

    假设我有一个叫bash的脚本 英尺·嘘 .

    我想这样称呼它

    foo.sh Here is a bunch of stuff on the command-line
    

    我希望它将所有的文本存储到一个变量中并打印出来。

    所以我的输出是:

    Here is a bunch of stuff on the command-line
    

    我该怎么做?

    3 回复  |  直到 11 年前
        1
  •  27
  •   David Z    17 年前
    echo "$*"
    

    执行您想要的操作,即打印出由空格分隔的整个命令行参数(或者,从技术上讲,无论 $IFS 是)。如果要将其存储到变量中,可以这样做

    thevar="$*"
    

    如果你的问题回答得不够好,我不知道还能说什么……

        2
  •  26
  •   Dennis Williamson    17 年前

    如果要避免涉及$ifs,请使用$@(或不要将$*括在引号中)

    $ cat atsplat
    IFS="_"
    echo "     at: $@"
    echo "  splat: $*"
    echo "noquote: "$*
    
    $ ./atsplat this is a test
         at: this is a test
      splat: this_is_a_test
    noquote: this is a test
    

    IFS行为也遵循变量赋值。

    $ cat atsplat2
    IFS="_"
    atvar=$@
    splatvar=$*
    echo "     at: $atvar"
    echo "  splat: $splatvar"
    echo "noquote: "$splatvar
    
    $ ./atsplat2 this is a test
         at: this is a test
      splat: this_is_a_test
    noquote: this is a test
    

    请注意,如果分配给$ifs是在分配$splatvar之后进行的,那么所有输出都将是相同的(在“atsplat2”示例中,ifs将不起作用)。

        3
  •  0
  •   Ayman Hourieh    17 年前

    看看 $* 变量。它将所有命令行参数组合为一个。

    echo "$*"
    

    这应该是你想要的。

    More info here.

    推荐文章