10

A few posts ago someone asked how to show memory in percentage. Someone replied with:

free | awk '/^Mem/ { printf("free: %.2f %\n", $4/$2 * 100.0) }'

I was wondering if I can turn this command into an alias in ~/.bashrc. But the syntax of alias is:

alias aliasname='command'

How can I do this? That command contains both ' and ". I tried different ways, but it didn't work. Is this even possible? Am I missing something?

  • 5
    To avoid quoting hell it might be easier to just define a function in such cases. – nohillside Dec 29 '18 at 14:05
  • 1
    @nohillside functions are generally more useful/powerful anyway – D. Ben Knoble Dec 29 '18 at 14:27
  • 1
    aliasname() { free | awk '/^Mem/ { printf("free: %.2f %\n", $4/$2 * 100.0) }'; } -- still just one line, no changes to quoting/escaping/etc needed at all. There's a reason the freenode #bash channel !alias factoid is (well, was, but for most of the factoid bot's life some variant of): If you have to ask, use a function instead. – Charles Duffy Dec 30 '18 at 03:51

2 Answers2

18

Saying that the syntax of an alias is alias aliasname='command' is a bit misleading, as it seems to imply that the single quotes are part of the syntax. They are not. The part after the equal sign is similar to variable assignments, in that it can be any shell word, composed either of plain characters (without quotes), or a quoted string, or a combination.

These are all valid, and the last three equivalent:

alias ks=ls
alias ls='ls -l'
alias ls="ls -l"
alias ls=ls\ -l

So, all you need to do is to escape the quotes properly to have them inside the alias value.

See, e.g. this answer and other answers to e.g. these question for discussion on that:

Or, use function instead of a alias to get rid of quoting issues completely:

freemem() {
    free | awk '/^Mem/ { printf("free: %.2f %\n", $4/$2 * 100.0) }'
}
ilkkachu
  • 138,973
8

You need:

alias aliasname="free | awk '/^Mem/ { printf(\"free: %.2f %\n\", \$4/\$2 * 100.0) }'"

Notice that you need to escape both " and $.