将命令作为参数传递给bash脚本 [英] pass a command as an argument to bash script
问题描述
如何将命令作为参数传递给bash脚本?在以下脚本中,我尝试执行此操作,但是它不起作用!
How do I pass a command as an argument to a bash script? In the following script, I attempted to do that, but it's not working!
#! /bin/sh
if [ $# -ne 2 ]
then
echo "Usage: $0 <dir> <command to execute>"
exit 1;
fi;
while read line
do
$($2) $line
done < $(ls $1);
echo "All Done"
此脚本的示例用法为
./myscript thisDir echo
执行上面的调用应该回显 thisDir
目录中所有文件的名称.
Executing the call above ought to echo the name of all files in the thisDir
directory.
推荐答案
您的命令"echo"命令已从$ line中的子段隐藏"在子外壳中.
your command "echo" command is "hidden" inside a sub-shell from its argments in $line.
我想我理解您尝试使用 $($ 2)
进行的操作,但是它可能会过大,除非不是全部,所以
I think I understand what your attempting in with $($2)
, but its probably overkill, unless this isn't the whole story, so
while read line ; do
$2 $line
done < $(ls $1)
应与 thisDir echo
一起用于您的示例.如果您确实需要cmd替换和subshell,请给您输入参数,以便他们可以互相看到:
should work for your example with thisDir echo
. If you really need the cmd-substitution and the subshell, then put you arguments so they can see each other:
$($2 $line)
正如D.S.所提到的,您可能需要 eval
之前的任何一个.
And as D.S. mentions, you might need eval
before either of these.
IHTH
这篇关于将命令作为参数传递给bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!