Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash_aliases and awk escaping of quotes

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.

like image 692
Massagran Avatar asked Jan 28 '13 11:01

Massagran


People also ask

How do you escape a quote in a shell script?

Escape with a backslash every double quote character and every backslash character: " ==> \", \ ==> \\

How do you escape quotes in Alias?

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 ( ' ).

How do you escape a single quote within a single quote?

' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.

How do you escape a single quote in Unix?

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.


2 Answers

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}'
}
like image 137
chepner Avatar answered Oct 21 '22 09:10

chepner


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}"'
like image 39
Thor Avatar answered Oct 21 '22 08:10

Thor