CLI 和 for 循环中的变量替换

CLI 和 for 循环中的变量替换

我很确定这个问题已经以某种形式被问到了,我只是无法找到一个好的搜索结果。

我想要一个可以执行 N 次操作的脚本,并且我可以将要发出 N 次的命令作为变量传递给该脚本。一般来说,该命令可能会使用迭代器值来更改某些内容。例如我想做类似的事情

~> doNtimes.sh 10 0 "ls *$(($2 + $i ))*.gnu | wc -l;"

其中 doNtime.sh 类似于

  for ((i=0; i < $1; ++i)); do 
       echo "iterator=$i"; 
       $3
  done

当然,目前双引号的使用让我失败了。我尝试过使用单引号,但也不起作用(尽管出于不同的原因)。事实上,我有带空格的变量并包含要在脚本中求值的变量,这使得我无法找到正确的语法......有什么想法吗?

答案1

您需要评估:

for ((i=0; i < $1; ++i)); do 
    echo "iterator=$i"; 
    # for debugging
    echo eval "$3"
    eval "$3"
done

当然,您必须注意命令字符串中的正确引用。从这个意义上说,您的示例ls *$(($2 + $i ))*.gnu | wc -l是危险的,因为变量引用是""在脚本运行之前在 ie 中解析的。您需要单引号:

doNtimes.sh 10 0 'ls *$(($2 + $i ))*.gnu | wc -l'

答案2

yes _do | head -n 10 | 3<&0 0>&- \
<<\INIT sh -s -- my args
    alias _do='echo these are "$@."'
    exec <&3 3>&- 
#END
INIT

你也可以很容易地强行喂贝壳。xargs也可以。

输出:

these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.

相关内容