How to escape single quotes correctly creating an alias
Solution 1
To make this an alias, which is possible, you need to use double quotes around the entire value for the alias. You'll also need to escape a few things within the alias as a result, and you need to escape any of the field arguments to awk
since these will get interpreted as arguments by Bash as well when you're setting the alias.
This worked for me:
$ alias mm="ps -u $USER -o pid,rss,command | \
awk '{print \$0}{sum+=\$2} END {print \"Total\", sum/1024, \"MB\"}'"
In the above I've done the following:
-
Double quotes around alias' value
alias mm="ps -u ...."
-
Escaped awk's double quotes
awk '{print \$0}{sum+=\$2} END {print \"Total\", sum/1024, \"MB\"}
-
Escaped awk's fields
awk '{print \$0}{sum+=\$2} END
Would I use this?
Probably not, I'd switch this to a Bash function instead, since it'll be easier to maintain and understand what's going on, but here's the alias if you still want it.
Solution 2
Can you help me understand how to create this alias?
May I advise you to create a function if you use bash and put it in .bashrc?
mm() {
ps -u "$USER" -o pid,rss,command |
awk '{print $0}{sum+=$2}
END {print "Total", sum/1024, "MB"}'
}
If it's bash
, variables need to be quoted. In a function, no need to put everything on one line.
Solution 3
Here is escaped command:
alias mm='ps -u $USER -o pid,rss,command | \
awk '\''{print $0}{sum+=$2} END {print "Total", sum/1024, "MB"}'\'
Example of escaping quotes in shell:
$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc
It's simply done by finishing already opened one ('
), placing escaped one (\'
), then opening another one ('
).
Alternatively:
$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc
It's done by finishing already opened one ('
), placing quote in another quote ("'"
), then opening another one ('
).
Related: How to escape single-quotes within single-quoted strings? at stackoverflow SE
Related videos on Youtube
Paolo
Please forgive my ignorance. Self reminders I'm here to learn. Learning is an experience, everything else is just information. (A.Einstein)
Updated on September 18, 2022Comments
-
Paolo over 1 year
I've been given this one-liner to know how much memory my processes consume.
$ ps -u $USER -o pid,rss,command | \ awk '{print $0}{sum+=$2} END {print "Total", sum/1024, "MB"}'
Now I'd like to create an alias for that command, but have an issue escaping
'
characters:$ alias mm=ps -u $USER -o pid,rss,command | \ awk '{print $0}{sum+=$2} END {print "Total", sum/1024, "MB"}' bash: alias: -u: not found bash: alias: myuser: not found bash: alias: -o: not found bash: alias: pid,rss,command: not found Total 0 MB
I tried to escape the single quotes, but still it doesn't work.
$ alias mm='ps -u $USER -o pid,rss,command | \ awk \'{print $0}{sum+=$2} END {print "Total", sum/1024, "MB"}\'' >
Can you help me understand how to create this alias?
-
Adrian Pronk over 9 years
-