2

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?

1
  • Presumably in the original, there's no space between the two equal signs in the awk script? Commented Apr 13, 2012 at 6:37

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Agreed, though I concluded that the module name was unlikely to contain shell metacharacters.
0

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.

2 Comments

That's part of the story; the other part is that the shell variable $module had to be added to the script, which is why single quotes were not used.
There are better ways to do this - either using option -v as you pointed out in your answer, or just by coding "'"$module"'" within a single-quoted script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.