bash 在 shell 脚本中连接命令字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18596857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate command string in a shell script
提问by Brian
I am maintaining an existing shell script which assigns a command to a variable in side a shell script like:
我正在维护一个现有的 shell 脚本,它将命令分配给一个 shell 脚本中的变量,例如:
MY_COMMAND="/bin/command -dosomething"
and then later on down the line it passes an "argument" to $MY_COMMAND by doing this :
然后稍后它通过这样做将“参数”传递给 $MY_COMMAND :
MY_ARGUMENT="fubar"
$MY_COMMAND $MY_ARGUMENT
The idea being that $MY_COMMAND
is supposed to execute with $MY_ARGUMENT
appended.
这个想法$MY_COMMAND
应该以$MY_ARGUMENT
附加的方式执行。
Now, I am not an expert in shell scripts, but from what I can tell, $MY_COMMAND
does not execute with $MY_ARGUMENT
as an argument. However, if I do:
现在,我不是 shell 脚本方面的专家,但据我所知,$MY_COMMAND
不会$MY_ARGUMENT
作为参数执行。但是,如果我这样做:
MY_ARGUMENT="itworks"
MY_COMMAND="/bin/command -dosomething $MY_ARGUMENT"
It works just fine.
它工作得很好。
Is it valid syntax to call $MY_COMMAND $MY_ARGUMENT
so it executes a shell command inside a shell script with MY_ARGUMENT
as the argument?
调用的语法是否有效,$MY_COMMAND $MY_ARGUMENT
以便它在 shell 脚本中使用MY_ARGUMENT
作为参数执行 shell 命令?
回答by konsolebox
With Bash you could use arrays:
使用 Bash,您可以使用数组:
MY_COMMAND=("/bin/command" "-dosomething") ## Quoting is not necessary sometimes. Just a demo.
MY_ARGUMENTS=("fubar") ## You can add more.
"${MY_COMMAND[@]}" "${MY_ARGUMENTS[@]}" ## Execute.
回答by Aleks-Daniel Jakimenko-A.
It works just the way you expect it to work, but fubar
is going to be the second argument ( $2
) and not $1
.
So if you echo
arguments in your /bin/command
you will get something like this:
它按照您期望的方式工作,但fubar
将成为第二个参数 ( $2
) 而不是$1
。
所以如果你echo
在你的论据中,/bin/command
你会得到这样的东西:
echo "" # prints '-dosomething'
echo "" # prints 'fubar'