我需要我的bashscript将其所有参数都捕获到一个文件中.我尝试使用cat它,因为我需要添加很多行:
#!/bin/sh
cat > /tmp/output << EOF
I was called with the following parameters:
"$@"
or
$@
EOF
cat /tmp/output
Run Code Online (Sandbox Code Playgroud)
这导致以下输出
$./test.sh "dsggdssgd" "dsggdssgd dgdsdsg"
I was called with the following parameters:
"dsggdssgd dsggdssgd dgdsdsg"
or
dsggdssgd dsggdssgd dgdsdsg
Run Code Online (Sandbox Code Playgroud)
我不想要这两件事:我需要在命令行上使用的确切引用.我怎样才能做到这一点?我一直认为$@在报价方面做的一切都是正确的.
好吧,你是对的,"$@"每个arg都有args包含空格.但是,由于shell 在执行命令之前执行引用删除,因此您永远无法知道引用args的确切方式(例如,无论是单引号还是双引号,还是反斜杠或其任何组合 - 但您不应该知道,因为所有你应该关心的是参数值).
放置"$@"在here-document中是没有意义的,因为你丢失了关于每个arg开始和结束的位置的信息(它们与中间的空间连接).这是一种看待这个的方法:
$ cat test.sh
#!/bin/sh
printf 'I was called with the following parameters:\n'
printf '"%s"\n' "$@"
$ ./test.sh "dsggdssgd" "dsggdssgd dgdsdsg"
I was called with the following parameters:
"dsggdssgd"
"dsggdssgd dgdsdsg"
Run Code Online (Sandbox Code Playgroud)