Bash 如何在shell脚本中从变量运行命令
在shell脚本中将命令分配给某个变量后,如何运行该命令? 例子: 命令\u name=echo 现在,有没有办法用“$command\u name hello world”代替“echo hello world” 在脚本文件中为我工作 在脚本文件中为我工作是的。确切的代码(Bash 如何在shell脚本中从变量运行命令,bash,shell,sh,Bash,Shell,Sh,在shell脚本中将命令分配给某个变量后,如何运行该命令? 例子: 命令\u name=echo 现在,有没有办法用“$command\u name hello world”代替“echo hello world” 在脚本文件中为我工作 在脚本文件中为我工作是的。确切的代码($command\u name hello world)将起作用 确保引号(如果存在)仅放在命令名和每个单独参数的周围。如果在整个字符串周围加上引号,它会将整个字符串解释为命令名,这不是您想要的 例如: command_na
$command\u name hello world
)将起作用
确保引号(如果存在)仅放在命令名和每个单独参数的周围。如果在整个字符串周围加上引号,它会将整个字符串解释为命令名,这不是您想要的
例如:
command_name="echo"
$command_name hello world
将被解释为:
echo hello world
"echo hello world"
(有效),鉴于:
command_name="echo"
"$command_name hello world"
command_name="echo hello world"
$command_name
被解释为:
echo hello world
"echo hello world"
这不起作用,因为它试图找到一个名为echo hello world
的命令,而不是将hello和world解释为参数
同样地
command_name="echo hello world"
"$command_name"
由于同样的原因失败,鉴于:
command_name="echo"
"$command_name hello world"
command_name="echo hello world"
$command_name
有效。是。确切的代码($command\u name hello world
)将起作用
确保引号(如果存在)仅放在命令名和每个单独参数的周围。如果在整个字符串周围加上引号,它会将整个字符串解释为命令名,这不是您想要的
例如:
command_name="echo"
$command_name hello world
将被解释为:
echo hello world
"echo hello world"
(有效),鉴于:
command_name="echo"
"$command_name hello world"
command_name="echo hello world"
$command_name
被解释为:
echo hello world
"echo hello world"
这不起作用,因为它试图找到一个名为echo hello world
的命令,而不是将hello和world解释为参数
同样地
command_name="echo hello world"
"$command_name"
由于同样的原因失败,鉴于:
command_name="echo"
"$command_name hello world"
command_name="echo hello world"
$command_name
有效。命令\u name='echo'
$command\u name“Hello World”command\u name='echo'
$command\u name“Hello World”您可以使用
eval
进行以下操作:
假设您有一个input\u文件
,该文件具有以下内容:
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
:
假设您有一个input\u文件
,该文件具有以下内容:
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
使用
bash
数组(这是有参数时的最佳实践):
使用
bash
数组(这是有参数时的最佳实践):
我的情况也是如此。但是,当我尝试添加参数时,它会显示一个错误(“未找到命令”),在我的情况下,替换也起作用。但是,当我尝试添加参数时,它会显示一个错误(“未找到命令”)Avoid
eval
,无论何时何地,它都有引起bug的良好声誉。Avoideval
无论何时何地,它都有引起bug的良好声誉。