简体   繁体   中英

Escaping awk parameters inside a Bash variable

I want to store an awk command in a variable for later using in an automated script.

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 -v par="eth0" '/^iface/ && $2==par {print}' /etc/network/interfaces

(This awk normally would print something like 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. 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. For example (the $ is my prompt):

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

$ auto_script
hello world

Just do the same for your awk script:

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.

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 . As a result you awk(1) does not get a proper program to run and you get an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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