2012-11-10 134 views
2

我想改變下面的bash函數來執行每個命令參數。但是當我運行這個腳本時,第一個echo會按照預期工作,但第二個echo嘗試附加到scratch.txt文件並不會真正執行。它只是回顯到提示中。bash腳本如何從變量執行命令

#!/bin/sh 
clear 

function each(){ 
    while read line; do 
    for cmd in "[email protected]"; do 
     cmd=${cmd//%/$line} 
     printf "%s\n" "$cmd" 
     $cmd 
    done 
    done 
} 

# pipe in the text file and run both commands 
# on each line of the file 
cat scratch.txt | each 'echo %' 'echo -e "%" >> "scratch.txt"' 

exit 0 

如何獲取$ cmd變量作爲命令執行?

我發現從2回答這裏的原代碼: xargs with multiple commands as argument

+2

使用'eval「$ cmd」' –

回答

4

你想eval。這是邪惡的。或者至少是危險的。請在BashFAQ #48處閱讀全部內容。