bash 执行包含来自 shell 变量的引号的命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11079342/
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-09 22:15:53  来源:igfitidea点击:

Execute command containing quotes from shell variable

bashshell

提问by Markus Kreusch

I'm currently having problems to execute a command from a shell variable.

我目前在从 shell 变量执行命令时遇到问题。

In general the following works as expected:

一般来说,以下工作按预期工作:

COMMAND="echo A"
echo $COMMAND
$COMMAND

produces:

产生:

echo A
A

But if I do

但如果我这样做

COMMAND="su aUser -s /bin/bash -c 'echo A'"
echo $COMMAND
$COMMAND

I get

我得到

su aUser -s /bin/bash -c 'echo A'
Password: 
A': -c: line 0: unexpected EOF while looking for matching `''
A': -c: line 1: syntax error: unexpected end of file

If I enter the line

如果我输入该行

su aUser -s /bin/bash -c 'echo A'

directly it works as expected.

直接它按预期工作。

It seems my assumption that $COMMAND is equal to entering the content as command directly is wrong.

似乎我的假设 $COMMAND 等于直接输入内容作为命令是错误的。

Questions

问题

1) Does anyone know how I can run the command from a variable?

1)有谁知道我如何从变量运行命令?

2) What exactly is the difference between

2)到底有什么区别

COMMAND="command"
$COMMAND

and

command

?

?

回答by glenn Hymanman

Arrays are useful to keep your parameters whole:

数组对于保持参数完整很有用:

command=(su aUser -s /bin/bash -c 'echo A')

and invoke it exactly like this:

并完全像这样调用它:

"${command[@]}"

回答by Igor Chubin

You need eval.

你需要eval.

$ eval $VARIABLE