Haiyuan Zhang
Haiyuan Zhang

Reputation: 42822

Using awk within bash

I'm reading ldd, and the following code is extracted from that:

major=$(awk "\\$2==\"$module\" {print \\$1}" /proc/devices)

I know what this one liner is doing, what I don't know is the why the escape character \ is used in it. Who can explain it to me?

Upvotes: 2

Views: 488

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754500

The shell variable $module has to be interpolated into the awk script, so the program can't be in single quotes. That means that any characters special to the shell must be protected with backslashes.

If the author preferred, the code could have been written like this:

major=$(awk -v module=$module '$2 == module { print $1 }' /proc/devices)

Testing the original code (after fixing up = = to ==, I get errors because of the double backslashes; they aren't necessary. Single backslashes would be sufficient, as in:

major=$(awk "\$2==\"$module\" {print \$1}" /proc/devices)

Upvotes: 4

ktf
ktf

Reputation: 7345

the author of this command line should have used single quotes (') instead of double quotes ("). By not doing so, he needs to quote Shell special characters so they may be passed to the awk-command.

Upvotes: 0

Related Questions