[英]bash alias command with both single and double quotes
I have this command that does what I want but I can't get to alias it in my .bashrc (note that it uses both single and double quotes):我有这个命令可以执行我想要的操作,但我无法在我的 .bashrc 中为其添加别名(请注意,它同时使用单引号和双引号):
svn status | awk '$1 =="M"{print $2;}'
I've tried:我试过:
alias xx="svn status | awk '$1 ==\"M\"{print $2;}'"
And some other common sense combinations with no luck.. I know that bash is very picky with quotes.. So what's the correct way to alias it and why ?还有其他一些没有运气的常识组合..我知道bash对引号非常挑剔..那么正确的别名方法是什么,为什么? Thanks
谢谢
你只需要正确地逃避它。
alias xxx="svn status | awk '\$1 ==\"M\"{print \$2;}'"
Here's something that accomplishes the same thing without using an alias.这是在不使用别名的情况下完成相同事情的东西。 Put it in a function in your .bashrc:
把它放在你的 .bashrc 中的一个函数中:
xx() {
svn status | awk '$1 =="M"{print $2;}'
}
This way you don't have to worry about getting the quotes just right.这样您就不必担心报价是否正确。 This uses the exact same syntax you would at the command line.
这与您在命令行中使用的语法完全相同。
Since Bash 2.04 there is a third (easier) way beside using a function or escaping the way @ffledgling did: using string literal syntax ( here is an excellent answer ).从Bash 2.04 开始,除了使用函数或逃避@ffledgling 所做的方式之外,还有第三种(更简单的)方法:使用字符串文字语法(这是一个很好的答案)。
So for example if you want to make an alias of this onliner it will end up being:因此,例如,如果您想为这个在线用户创建一个别名,它最终将是:
alias snap-removedisabled=$'snap list --all | awk \'$5~"disabled"{print $1" --revision "$3}\' | xargs -rn3 snap remove'
So you just have to add the $
in front of the string and escape the single quotes.所以你只需要在字符串前面添加
$
并转义单引号。
This brings a shellcheck warning you could probably safely disable with # shellcheck disable=SC2139
.这会带来一个 shellcheck 警告,您可以使用
# shellcheck disable=SC2139
安全地禁用# shellcheck disable=SC2139
。
You can revert the double and simple quotations, so that double quotations are outside of single quotations .您可以还原双引号和单引号,使双引号在单引号之外。
For example, this does not work:例如,这不起作用:
alias docker-table='docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Status}}"'
But this works:但这有效:
alias docker-table="docker ps --format 'table {{.ID}}\t{{.Image}}\t{{.Status}}'"
And when you check the actual alias interpreted, you can see the inner quotations are actually escaped.当您检查实际解释的别名时,您可以看到内部引号实际上已被转义。
$ alias docker-table
alias docker-table='docker ps --format '\''table {{.ID}}\t{{.Image}}\t{{.Status}}'\'''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.