2012-11-10 135 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处阅读全部内容。