Create Alias with Quotes in Bash – Handling ‘ and ” Characters

aliasbashquoting

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?

Best Answer

You need:

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

Notice that you need to escape both " and $.

Related Question