简体   繁体   English

在Bash变量中转义awk参数

[英]Escaping awk parameters inside a Bash variable

I want to store an awk command in a variable for later using in an automated script. 我想将awk命令存储在变量中,以便以后在自动化脚本中使用。

How do I store a command in a variable? 如何将命令存储在变量中?

AUTO_SCRIPT="cp a b"

How do I run the stored command? 如何运行存储的命令?

$AUTO_SCRIPT

Now I want to store an awk command in this script: 现在,我想在此脚本中存储一个awk命令:

awk -v par="eth0" '/^iface/ && $2==par {print}' /etc/network/interfaces

(This awk normally would print something like iface eth0 inet dhcp . (此awk通常会显示类似iface eth0 inet dhcp的内容

So I want to store it for later execution: 所以我想将其存储以供以后执行:

AUTO_SCRIPT="awk -v par=\"eth0\" '/^iface/ && $2==par {print}' /etc/network/interfaces"

However when trying to execute: 但是,当尝试执行时:

$AUTO_SCRIPT
awk: cmd. line:1: '/^iface/
awk: cmd. line:1: ^ invalid char ''' in expression

What have I tried? 我尝试了什么? Almost everything. 几乎所有的。 Escaping apostrophes with \\ character. 使用\\字符转义撇号。 Using qoute character instead of apostrophes. 使用qoute字符代替撇号。 Trying with ( and ) characters and so on. 尝试使用(和)字符等。 Nothing works. 什么都没有。

I would need some good idea here. 我这里需要一些好主意。

Don't save commands in variables, there's no reason to, its cludgy and error-prone. 不要将命令保存在变量中,这没有理由,因为它笨拙且容易出错。 Just create a shell function that calls the awk script instead. 只需创建一个调用awk脚本的shell函数即可。 For example (the $ is my prompt): 例如( $是我的提示):

$ auto_script() { echo 'hello world'; }

$ auto_script
hello world

Just do the same for your awk script: 只需对awk脚本执行相同的操作:

auto_script() { awk -v par='eth0' '/^iface/ && $2==par' /etc/network/interfaces; }

Putting the command in a function is the cleanest solution. 将命令放在函数中是最干净的解决方案。 The only other solution is to put the command in an array . 唯一的其他解决方案是将命令放入数组中

auto_script=( awk -v par="eth0" '/^iface/ && $2==par {print}' /etc/network/interfaces )

and then execute it like this 然后像这样执行它

"${auto_script[@]}"

Read that BashFAQ #50 link you were given. 阅读该BashFAQ#50链接。

It looks like you cannot unless you use another mechanism like arrays. 除非您使用数组之类的其他机制,否则您似乎无法。

When you call $AUTO_SCRIPT the shell splits the content by whitespace resulting in the following arguments: awk , -v , par=\\"eth0\\" , '/^iface/ , && , $2==par , {print}' , /etc/network/interfaces . 当您调用$AUTO_SCRIPT ,shell会按空格将内容拆分,从而产生以下参数: awk-vpar=\\"eth0\\"'/^iface/&&$2==par{print}'/etc/network/interfaces As a result you awk(1) does not get a proper program to run and you get an error. 结果,awk(1)无法运行适当的程序,并且出现错误。

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

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