如何将“$@”的值作为单个参数传递?

How to pass the value of "$@" as a single argument?

我写了下面的 Go 代码。

package main

import (
  "fmt"
  "os"
  "strings"
)

func main() {
  fmt.Println(os.Args)
}

然后编译...

$ go build -o out

并创建了以下脚本 a.sh:

#! /bin/bash

set -eu

./out "--opt1" "$@"

然后运行a.sh结果是:

$ a.sh hoge --foo bar
[./out --opt1 hoge --foo bar ]

我想获取 $@ 作为字符串。结果我预计 [./out --opt1 "hoge --foo bar" ]

但是它们被拆分为数组元素(通过空格或 $IFS?)。 有没有办法得到$@

您可能想改用 "$*"

这是一个例子:

函数 f1 使用 "$@" 来打印它的参数,而 f2 使用 "$*" 来做同样的事情。

f1() { printf '<%s>\n' "$@"; }
f2() { printf '<%s>\n' "$*"; }

注意它们输出的差异:

$ f1 a b c
$ <a>
$ <b>
$ <c>
$ f2 a b c
$ <a b c>

$@$*的区别:

  • 没有双引号(不要这样做!): 没有区别。

  • 带双引号: "$@" 扩展为每个位置参数作为其自己的参数:"" "" ""...,而 "$*" 扩展为单个参数 "cc..." , 其中 'c' 是 IFS.

  • 的第一个字符

转到代码

package main

import (
    "fmt"
    "os"
)   

func main() {
    for i, arg := range os.Args {
        fmt.Printf("Args[%d] = %s\n", i, arg)
    }
}

Bash代码

#! /bin/bash

set -eu

./out "--opt1" "$*"

输出

$ ./a.sh hoge --foo bar
Args[0] = ./out
Args[1] = --opt1
Args[2] = hoge --foo bar

说明

3.2.5. Special parameters of the Bash Guide for Beginners 状态:

  • $* — Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.
  • $@ — Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word.

The implementation of "$" has always been a problem and realistically should have been replaced with the behavior of "$@". In almost every case where coders use "$", they mean "$@". "$*" Can cause bugs and even security holes in your software.