如何在將命令分配給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[@]}"
是的,它現在可以工作!非常感謝你 –