【问题标题】:Bash script how to execute a command from a variableBash脚本如何从变量执行命令
【发布时间】:2012-10-30 16:47:56
【问题描述】:

我正在尝试更改下面的 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

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

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

【问题讨论】:

    标签: bash


    【解决方案1】:

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

    【讨论】:

    • Re "You want eval": 你的意思是"You don't want eval"?还是“你想要评估,但是”?还是别的什么?
    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 2011-10-16
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 2016-12-28
    相关资源
    最近更新 更多