Bash脚本-可变内容作为要运行的命令 [英] Bash script - variable content as a command to run
问题描述
我有一个Perl脚本,该脚本为我提供了一个与文件行相对应的已定义列表随机数.接下来,我想使用sed
从文件中提取这些行.
I have a Perl script that gives me a defined list random numbers that correspond to the lines of a file. Next I want to extract those lines from the file using sed
.
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var=$(perl test.pl test2 $count)
变量var
返回类似cat last_queries.txt | sed -n '12p;500p;700p'
的输出.问题是我无法运行最后一条命令.我尝试使用$var
,但输出不正确(如果我手动运行该命令,它将正常运行,因此那里没有问题).正确的方法是什么?
The variable var
returns an output like: cat last_queries.txt | sed -n '12p;500p;700p'
. The problem is that I can't run this last command. I tried with $var
, but the output is not correct (if I run manually the command it works fine, so no problem there). What is the correct way to do this?
P.S:当然,我可以在Perl中完成所有工作,但是我正在尝试学习这种方式,因为它可以在其他情况下为我提供帮助.
P.S: Sure I could do all the work in Perl, but I'm trying to learn this way, because it could help me in other situations.
推荐答案
您只需要这样做:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
但是,如果要稍后再调用Perl命令,这就是为什么要将其分配给变量的原因,那么:
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
根据Bash的帮助:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
这篇关于Bash脚本-可变内容作为要运行的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!