1

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';
  • You should rather state what shell this is, not that it's on Linux. I mean the tags. – user147505 Mar 26 '18 at 20:37
  • So replace linux with version 4.1.2(1)-release or what should the tag be? – chris85 Mar 26 '18 at 20:39
  • It's Bash. bashrc is a config file of Bash. – user147505 Mar 26 '18 at 20:47
  • Aliases have two advantages over shell scripts or shell functions, but if you have neither of those reasons to use them, then you could consider not using them. – can-ned_food Mar 27 '18 at 3:02
  • @can-ned_food What are the two advantages you are referring to? Running who_con seems like the easiest way to get the result of who | awk '{ print $1}' | sort | uniq -c | sort. – chris85 Mar 27 '18 at 3:13
6

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
| improve this answer | |
  • @chris85 I don't see cat in your question. I added the other possible quoting to my answer. – user147505 Mar 26 '18 at 20:36
  • Oh, I meant awk not cat. I was trying cat before. I'll accept this in 3 minutes. – chris85 Mar 26 '18 at 20:37
  • 1
    Ah, that's right! The whole line is expanded twice by the shell, and the single quotes only blocks either the first or the second time from affecting awk's argument, depending on whether they're inner or outer. I suppose alias what='who | awk '\''{print $1}'\'' | ...' would also work, but is overkill with only one inner meta-character – jpaugh Mar 26 '18 at 20:52

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.