如何在将命令分配给shell脚本中的某个变量后运行命令? 例如: command_name = echo如何从shell脚本中的变量运行命令
现在,有没有办法使用“$ command_name hello world”而不是“echo hello world”?
如何在将命令分配给shell脚本中的某个变量后运行命令? 例如: command_name = echo如何从shell脚本中的变量运行命令
现在,有没有办法使用“$ command_name hello world”而不是“echo hello world”?
是为我工作。确切的代码($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
作品。
#!/bin/bash
var="command"
"$var"
在脚本文件
替代在我的情况也可以。但是当我尝试添加参数时,它显示一个错误(“找不到命令”) –
COMMAND_NAME = '回声'
$ COMMAND_NAME的 “Hello World”
您可以使用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
'eval'是邪恶的! –
随时随地避免'eval' - 它在造成错误方面享有良好声誉。 –
随着bash
阵列(这是最好的做法,当你有参数):
commandline=("echo" "Hello world")
"${commandline[@]}"
是的,它现在可以工作!非常感谢你 –