[英]Bash script - variable content as a command to run
我有一个 Perl 脚本,它为我提供了与文件行相对应的已定义随机数列表。 接下来,我想使用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'
cat last_queries.txt | sed -n '12p;500p;700p'
。 问题是我无法运行最后一个命令。 我尝试使用$var
,但输出不正确(如果我手动运行命令它工作正常,所以没有问题)。 这样做的正确方法是什么?
PS:当然我可以在 Perl 中完成所有工作,但我正在尝试以这种方式学习,因为它可以在其他情况下帮助我。
你只需要这样做:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
然而,如果你想稍后调用你的 Perl 命令,这就是你想将它分配给一个变量的原因,那么:
#!/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.
您可能正在寻找eval $var
。
有两种在 shell 脚本中执行字符串命令的基本方法,无论它是否作为参数给出。
COMMAND="ls -lah"
$(echo $COMMAND)
或者
COMMAND="ls -lah"
bash -c $COMMAND
如果您有多个变量包含正在运行的命令的参数,而不仅仅是单个字符串,则不应直接使用 eval,因为它在以下情况下会失败:
function echo_arguments() {
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"
echo "Argument 4: $4"
}
# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"
结果:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg
请注意,即使 "Some arg" 作为单个参数传递, eval
其读取为两个。
相反,您可以只使用字符串作为命令本身:
# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
"$@";
}
注意eval
的输出和新的eval_command
函数之间的区别:
eval_command echo_arguments arg1 arg2 "Some arg"
结果:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:
line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd
只是用你的文件代替。
在这个例子中,我使用了文件 /etc/password,使用了特殊变量${RANDOM}
(我在这里学到了)和你的sed
表达式,唯一的区别是我使用双引号而不是单引号来允许变量扩展。
更好的方法来做到这一点
使用函数:
# define it
myls() {
ls -l "/tmp/test/my dir"
}
# run it
myls
使用数组:
# define the array
mycmd=(ls -l "/tmp/test/my dir")
# run the command
"${mycmd[@]}"
cmd="ls -atr ${HOME} | tail -1" <br/>
echo "$cmd" <br/>
VAR_FIRST_FILE=$( eval "${cmd}" ) <br/>
或者
cmd=("ls -atr ${HOME} | tail -1") <br/>
echo "$cmd" <br/>
VAR_FIRST_FILE=$( eval "${cmd[@]}" )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.