Concatenate command string in a shell script

吃可爱长大的小学妹 提交于 2021-01-27 23:42:51

问题


I am maintaining an existing shell script which assigns a command to a variable in side a shell script like:

MY_COMMAND="/bin/command -dosomething"

and then later on down the line it passes an "argument" to $MY_COMMAND by doing this :

MY_ARGUMENT="fubar"

$MY_COMMAND $MY_ARGUMENT

The idea being that $MY_COMMAND is supposed to execute with $MY_ARGUMENT appended.

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:

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?


回答1:


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:

echo "$1" # prints '-dosomething'
echo "$2" # prints 'fubar'



回答2:


With Bash you could use arrays:

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.


来源:https://stackoverflow.com/questions/18596857/concatenate-command-string-in-a-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!