I'm trying to create an alias for a command to see the memory use,
ps -u user -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}'
but, the naive,
#.bash_aliases
alias totalmem='ps -u user -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}''
gives errors:
-bash: alias: END: not found
-bash: alias: {print: not found
-bash: alias: sum/1024}: not found
I've tried with double quotes,
totalmem ="ps ... |awk '{sum+=$1} END {print sum/1024}'"
, or
totalmem ='ps ... |awk "{sum+=$1} END {print sum/1024}"'
,
escaping,
totalmem ='ps ... |awk \'{sum+=$1} END {print sum/1024}\''
,
or escaping double quotes ... but I can't seem to make it work.
totalmem ='ps ... |awk \"{sum+=$1} END {print sum/1024}\"'
,
gives the error
awk: "{sum+=}
awk: ^ unterminated string
Any tips appreciated.
Escape with a backslash every double quote character and every backslash character: " ==> \", \ ==> \\
If it's bash , variables need to be quoted. In a function, no need to put everything on one line. Show activity on this post. It's simply done by finishing already opened one ( ' ), placing escaped one ( \' ), then opening another one ( ' ).
' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.
A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word.
You can avoid quoting issues by using a shell function instead of an alias:
totalmem () {
ps -u user -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}'
}
This is also more flexible, as you could allow totalmem
to take arguments, such as a user name to pass to the -u
option of ps
, as in this example:
totalmem () {
ps -u "$1" -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}'
}
You almost have it, the $
will be expanded in double-quotes, so that needs extra escaping:
alias totalmem='ps -u user -o rss,command | grep -v peruser | awk "{sum+=\$1} END {print sum/1024}"'
Or with the pattern inside awk
as suggested by iiSeymour:
alias totalmem='ps -u user -o rss,command | awk "!/peruser/ {sum+=\$1} END {print sum/1024}"'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With