bash bash脚本如何从变量执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13323778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:45:35  来源:igfitidea点击:

bash script how to execute a command from a variable

bash

提问by ooXei1sh

I am trying to alter the bash function below to execute each command argument. But when I run this script the first echo works as intended but the second echo that attempts to append to the scratch.txt file does not actually execute. It just gets echo'd into the prompt.

我正在尝试更改下面的 bash 函数以执行每个命令参数。但是当我运行这个脚本时,第一个回声按预期工作,但试图附加到scratch.txt 文件的第二个回声实际上没有执行。它只是被回显到提示中。

#!/bin/sh
clear

function each(){
  while read line; do
    for cmd in "$@"; 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

how do I get the $cmd variable to execute as a command?

如何让 $cmd 变量作为命令执行?

I found the original code from answer 2 here: xargs with multiple commands as argument

我在这里找到了答案 2 的原始代码: xargs with multiple commands as argument

回答by ghoti

You want eval. It's evil. Or at least, dangerous. Read all about it at BashFAQ #48.

你要eval。这是邪恶的。或者至少,危险。在BashFAQ #48阅读所有相关信息。