Fixing Linux Command Not Functioning as Alias

aliasbashcentos

I've created a command to count the number of sessions each user on our server has. It is:

who | awk '{ print $1}' | sort | uniq -c | sort

which works fine, but when I move this into an alias on the server I'm only get the return of who,

alias who_con="who | awk '{ print $1}' | sort | uniq -c | sort";

I thought it might have been the double quotes so I tried single quotes for the encapsulation but I have the same behavior,

alias who_con='who | awk "{ print $1}" | sort | uniq -c | sort';

Best Answer

You need to escape the dollar in $1.

$ alias wW="who | awk '{ print \$1}' | sort | uniq -c | sort"
$ wW
      1 tomasz

$1 should be expanded by awk, not by the shell. Without the additional escape, it's expanded by the shell. You need one more level of escape. This will also do:

$ alias who_con='who | awk "{ print \$1}" | sort | uniq -c | sort';
$ who_con
      1 tomasz
Related Question