简体   繁体   English

Bash变量管道在别名内不起作用?

[英]Bash variable piping not working within an alias?

I tried creating the following as an alias in my .bash_profile. 我尝试在.bash_profile中创建以下作为别名。

alias die_memcached_die="ps -ef | awk '/memcached/ && !/awk/ {print $2}' | xargs kill -9"

It works fine if I run the commands directly on the terminal 如果我直接在终端上运行命令,它工作正常

ps -ef | awk '/memcached/ && !/awk/ {print $2}' | xargs kill -9

or if I create a bash script to run it. 或者如果我创建一个bash脚本来运行它。

Just curious why this doesn't work in an alias? 只是好奇为什么这不能用于别名?

The problem is that you wrap your alias definition in double quotes and so the shell immediately expands $2 and your awk script isn't what you expect it to be. 问题是您将别名定义包装在双引号中,因此shell会立即扩展$2并且您的awk脚本不是您期望的那样。

$ cat aa
alias die_memcached_die="ps -ef | awk '/memcached/ && !/awk/ {print $2}' | xargs kill -9"

echo 'Alias command run is:'
echo 'alias die_memcached_die="ps -ef | awk '\''/memcached/ && !/awk/ {print $2}'\'' | xargs kill -9"'
echo 'Alias actually is:'
alias die_memcached_die

alias die_memcached_die='ps -ef | awk '\''/memcached/ && !/awk/ {print $2}'\'' | xargs kill -9'

echo 'Alias actually is:'
alias die_memcached_die

$ /bin/bash aa
Alias command run is:
alias die_memcached_die="ps -ef | awk '/memcached/ && !/awk/ {print $2}' | xargs kill -9"
Alias actually is:
alias die_memcached_die='ps -ef | awk '\''/memcached/ && !/awk/ {print }'\'' | xargs kill -9'
Alias actually is:
alias die_memcached_die='ps -ef | awk '\''/memcached/ && !/awk/ {print $2}'\'' | xargs kill -9'

That being said both of the comments on the OP about this being a poor alias and a poor idea are correct. 可以说,关于OP的两个评论都是关于这是一个糟糕的别名和一个糟糕的想法是正确的。

Alias should be enclosed in single quotes to prevent the shell from interpolating variables that are preceded by $ . 别名应该用单引号括起来,以防止shell插入前面带有$变量。

You should have your alias like: 你应该有你的别名:

alias die_memcached_die='ps -ef | awk "/memcached/ && !/awk/ {print \$2}" | xargs kill -9'

You can have awk definition inside single quotes but then you need to make sure you escape them. 你可以在单引号内定义awk但是你需要确保你逃脱它们。

Also, have a look at functions too. 另外,也看看功能。 They provide better scalability and reliability over aliases. 它们提供了比别名更好的可扩展性和可靠性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM