I create an alias in ~/.cshrc like this

alias bw  "bjobs -w | awk '{print $7}'"

but it doesn't work at $7. How do I fix this ?


Try seeing what csh has defined your alias to, by typing this at the command prompt:

% alias bw

bjobs -w | awk '{print }'

What happened? the shell expanded a shell variable named $7, which happens to be nothing, and stuffed that null value in the alias definition.

So this suggests a solution itself, we need to quote the dollar in the $7, away from the prying eyes of the shell, so that it is entered literally into the alias' definition:

% alias bw "bjobs -w | awk '{print "\$"7}'"

Now when we test what the alias is:

% alias bw

bjobs -w | awk '{print $7}'

and this is exactly what you would type at the command line!

To perform the writing of the alias definition, we perform it in 3 steps:

 - The quoting is done by closing the double quotes just before the $ to
            come out of the alias' quoting.
 - Now the $ needs to be escaped via a backslash to stop it from being 
            expanded before the alias takes effect.
 - Start the double quotes to re-enter the alias' quoting.

** I wish I could draw this thing pictorially which makes it very trivial to understand.



alias bw 'bjobs -w | awk '\''{print $7}'\'''

csh quoting is painful.

  • This is not a problem that exists only in csh. The same problem applies to shells that implement the ksh like alias command, since the alias parameters in both cases need to go two times through the parser. The Bourne Shell for good reason implements a method to view and edit raw aliases. – schily Jun 14 '18 at 9:21
  • @schily Hmm, but in ksh, I can only just escape $ in $7. no? – cuonglm Jun 14 '18 at 9:31
  • If you like to have single quote characters inside a string surrounded by single quote characters, you always have this problem. – schily Jun 14 '18 at 9:33
  • 1
    Let me give an example with the Bourne Shell and an alias that I use to check man pages while writing them: alias mroff prints: mroff='dosh '\''soelim "$@" | tbl | nroff -u1 -Tlp -man - | col -x'\'' mroff' while alias -raw mroffprints: #b mroff dosh 'soelim "$@" | tbl | nroff -u1 -Tlp -man - | col -x' mroff The command doshis a Bourne Shell builtin to have inline shell scripts for parameterized aliases. – schily Jun 14 '18 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.