简体   繁体   English

从带有位置参数的字符串执行BASH shell

[英]BASH shell execution from string with positional parameters

When I try to run the code below, the shell is replacing (because they are not defined as a bash variable) $4 and $2 with blanks. 当我尝试运行以下代码时,shell用空格替换$ 4和$ 2(因为它们未定义为bash变量)。 My question is, how do I keep bash from trying to evaluate the positional parameters for awk as its variables? 我的问题是,如何避免bash尝试评估awk的位置参数作为其变量? I've tried putting double and single quotes around the positional parameters, however, that did not suppress bash from interpreting them as local variables instead of strings. 我试过在位置参数周围加上双引号和单引号,但这并没有抑制bash将其解释为局部变量而不是字符串。

This is what is returned when I echo "$x$i$y" 这是我echo "$x$i$y"

date -r /root/capture/capture11.mp4 | awk '{print }' | awk -F":" '/1/ {print }'

Code: 码:

#!/bin/sh
i=$(cat /etc/hour.conf)
x="date -r /root/capture/capture"
y=".mp4 | awk '{print $4}' | awk -F\":\" '/1/ {print $2}'"
$x$i$y

Any help would be greatly appreciated! 任何帮助将不胜感激!

Variables are interpolated inside double quotes. 变量用双引号内插。 Use single quotes, or escape them like \\$2 . 使用单引号,或使用\\$2对其进行转义。

However, the way you're trying to split up the command into separate variables won't work. 但是,您尝试将命令拆分为单独的变量的方式将不起作用。 Instead, you should use a function. 相反,您应该使用一个函数。 Then you don't need to deal with quotes and escaping at all. 然后,您根本不需要处理引号和转义符。 For instance: 例如:

do_thing() {
    date -r "/root/capture/capture$1.mp4" | awk '{print $4}' | awk -F':' '/1/ {print $2}'
}

do_thing "$(cat /etc/hour.conf)"

$4 is doubled quoted. $4被加倍引用。 Though there are single quotes, it is included in double quotes. 尽管有单引号,但它包含在双引号中。 So the single quotes are just part of the string and it won't keep the literal meaning of $ . 因此,单引号只是字符串的一部分,并且不会保留$的字面含义 So you can escape the $ : 这样就可以逃脱$

y=".mp4 | awk '{print \$4}' | awk -F\":\" '/1/ {print \$2}'"

Or, use single quotes around the whole part: 或者,在整个部分使用单引号:

y='.mp4 | awk "{print \$4}" | awk -F':' "/1/ {print \$2}"'

Concatenating variables like that to build a command line sort of works, but quotes within the variables don't quote anything, they'll just be taken as literal quotes. 串联变量一样,要建立一个命令行排序的作品,但这些变量引用不引用任何东西,他们就会被当作文字引号。

This sort of works (but is horrible): 这种作品(但很可怕):

$ x=prin; y="tf %f\\n"; z=" 123456789"
$ $x$y$z
123456789.000000

This doesn't do what you want: 这不能满足您的要求:

$ z='"foo bar"'; printf $y ; echo
"foo

Instead of one argument foo bar , printf gets the two arguments "foo and bar" . 代替一个参数foo barprintf获得了两个参数"foo and bar"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM