Daniel
Daniel

Reputation: 2592

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.

Upvotes: 2

Views: 499

Answers (3)

Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9127

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.

Upvotes: -1

glenn jackman
glenn jackman

Reputation: 246827

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.

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203635

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; }

Upvotes: 4

Related Questions