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 ?
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.
csh
. The same problem applies to shells that implement theksh
likealias
command, since thealias
parameters in both cases need to go two times through the parser. TheBourne Shell
for good reason implements a method to view and edit raw aliases. – schily Jun 14 '18 at 09:21ksh
, I can only just escape$
in$7
. no? – cuonglm Jun 14 '18 at 09:31alias mroff
prints:mroff='dosh '\''soelim "$@" | tbl | nroff -u1 -Tlp -man - | col -x'\'' mroff'
whilealias -raw mroff
prints:#b mroff dosh 'soelim "$@" | tbl | nroff -u1 -Tlp -man - | col -x' mroff
The commanddosh
is a Bourne Shell builtin to have inline shell scripts for parameterized aliases. – schily Jun 14 '18 at 09:35