如何从shell脚本中的变量运行命令

时间:2012-11-21 19:27:44

标签: bash shell sh

如何在shell脚本中将命令分配给某个变量后运行命令? 例: COMMAND_NAME =回声

现在,有没有办法使用“$ command_name hello world”代替“echo hello world”?

5 个答案:

答案 0 :(得分:3)

是。确切的代码($command_name hello world)将起作用。

确保引号(如果存在)仅放在命令名称和每个单独的参数周围。如果在整个字符串周围放置引号,它会将整个字符串解释为命令名称,这不是您想要的。

例如:

command_name="echo"
$command_name hello world

将被解释为:

echo hello world

(有效),而:

command_name="echo"
"$command_name hello world"

被解释为:

"echo hello world"

这不起作用,因为它试图找到一个名为echo hello world的命令,而不是将hello和world解释为参数。

类似地,

command_name="echo hello world"
"$command_name"

因同样的原因而失败,而:

command_name="echo hello world"
$command_name

作品。

答案 1 :(得分:1)

COMMAND_NAME = '回响'

$ command_name“Hello World”

答案 2 :(得分:0)

#!/bin/bash
var="command"
"$var"

在脚本文件中为我工作

答案 3 :(得分:0)

您可以使用eval

假设您有input_file,其中包含以下内容:

a        b             c  d e f   g

现在试试你的终端:

# this sed command coalesces white spaces
text='sed "s/ \+/ /g" input_file'

echo $text
sed "s/ \+/ /g" input_file

eval $text
a b c d e f g

答案 4 :(得分:0)

使用bash数组(当你有参数时这是最好的做法):

commandline=( "echo" "Hello world" )
"${commandline[@]}"
相关问题