bash_aliases and awk escaping of quotes

依然范特西╮ 提交于 2019-12-04 05:02:46

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

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

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