bash_aliases and awk escaping of quotes

别等时光非礼了梦想. 提交于 2019-12-12 08:46:52

问题


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.


回答1:


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}"'



回答2:


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}'
}



回答3:


Like this:

alias totalmem='ps -u user -o rss,command | grep -v peruser | awk '\''{sum+=$1} END {print sum/1024}'\'

Explanation: you may use different kind of quotes for the same argument, like "I'm double-quoted"'and I am $HOME-less'-and-i-am-not-quoted. Hence if you need a single quote inside single quotes, you can add '\'' which (1) terminates single quoting, (2) adds literal single quote with \', (3) starts single quoting again.

(Aliases of this size are something that's better done as functions).



来源:https://stackoverflow.com/questions/14560796/bash-aliases-and-awk-escaping-of-quotes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!