Puzzle time!

I found this alias recently in an old .bashrc copy:

alias dff='df -h | grep sdc | awk '"'"'{print $5}'"'"

The output is 2% which is the 5th column returned by df -h | grep sdc. So far so good.

The only thing I do not comprehend here is the quoting. It is mad!

There is a single quote opening the whole alias. Then right after awk there's a series of 5 quotes (single-double-single-double-single) and then another 4 at the end (single-double-single-double).

What the eff?

@xpil Thinking out loud:

The alias command does some escaping on its own. After doing an alias whatever=stuff assignment, check alias whatever to see what it did.
Constraint: The whole RHS of the assignment must be interpreted as a literal string to contain all the pipes.
Constraint: The awk ‘{print $5}’ bit must be in single quotes, else the $5 will be interpreted before being fed to awk.

Looks like:

‘df -h … awk ‘ is one string.
“‘“ is another string, concatenated to the first.
‘{print $5}’ is another string, put in single quotes to avoid interpolation, and concatenated.
“‘“ is the final string, concatenated.

2 & 4 bracket the brackets — awk wants them around the {print $5} to avoid its own interpolation.

Done! :-)

@xpil [To prove concatenation, at a terminal prompt, type 'l''s' and enter.]

@xpil Afaict this would be the correct way to insert a pair of single-quotes into a single-quoted string, without escaping with backslashes.

Using just double-quotes (for awk) within single-quotes (for alias) causes "$5" to evaluate when the alias is called, but before awk is called. Single-quotes (awk) within double-quotes (alias) evaluates "$5" even at the definition of this alias.

A more compact solution might be:

alias dff="df -h | grep sda | awk '{print \$5}'"

Sign in to participate in the conversation

Fosstodon is an English speaking Mastodon instance that is open to anyone who is interested in technology; particularly free & open source software.