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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:26:52  来源:igfitidea点击:

Concatenate command string in a shell script

bashshellscripting

提问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_COMMANDis supposed to execute with $MY_ARGUMENTappended.

这个想法$MY_COMMAND应该以$MY_ARGUMENT附加的方式执行。

Now, I am not an expert in shell scripts, but from what I can tell, $MY_COMMANDdoes not execute with $MY_ARGUMENTas 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_ARGUMENTso it executes a shell command inside a shell script with MY_ARGUMENTas 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 fubaris going to be the second argument ( $2) and not $1.
So if you echoarguments in your /bin/commandyou will get something like this:

它按照您期望的方式工作,但fubar将成为第二个参数 ( $2) 而不是$1
所以如果你echo在你的论据中,/bin/command你会得到这样的东西:

echo "" # prints '-dosomething'
echo "" # prints 'fubar'