比方说,你有一个Bash别名:
alias rxvt='urxvt'
这很好。
然而:
alias rxvt='urxvt -fg '#111111' -bg '#111111''
不管用,也不管用:
alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
那么,一旦有转义引号,如何在字符串中匹配开始和结束引号呢?
alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
看起来很笨拙,但如果允许像这样连接它们,它将表示相同的字符串。
我并没有特别提到引用问题,因为,有时候,考虑另一种方法是合理的。
rxvt() { urxvt -fg "#${1:-000000}" -bg "#${2:-FFFFFF}"; }
你可以调用它为:
rxvt 123456 654321
这个想法是你现在可以在不考虑引号的情况下使用别名:
alias rxvt='rxvt 123456 654321'
或者,如果你出于某种原因需要在所有调用中包含#:
rxvt() { urxvt -fg "${1:-#000000}" -bg "${2:-#FFFFFF}"; }
你可以调用它为:
rxvt '#123456' '#654321'
那么,当然,别名是:
alias rxvt="rxvt '#123456' '#654321'"
(哦,我想我确实提到了引用:)
另一种解决太多嵌套引用层问题的方法:
您试图将太多内容塞进太小的空间,因此使用bash函数。
问题是您试图有太多的嵌套级别,而基本的别名技术还不够强大。使用这样的bash函数,使单引号、双引号、反引号和传入的参数都像我们预期的那样正常处理:
lets_do_some_stuff() {
tmp=$1 #keep a passed in parameter.
run_your_program $@ #use all your passed parameters.
echo -e '\n-------------' #use your single quotes.
echo `date` #use your back ticks.
echo -e "\n-------------" #use your double quotes.
}
alias foobarbaz=lets_do_some_stuff
然后,您可以使用$1和$2变量以及单引号、双引号和反引号,而不用担心别名函数破坏它们的完整性。
这个程序输出:
el@defiant ~/code $ foobarbaz alien Dyson ring detected @grid 10385
alien Dyson ring detected @grid 10385
-------------
Mon Oct 26 20:30:14 EDT 2015
-------------
如果你已经安装了GNU Parallel,你可以使用它的内部引用:
$ parallel --shellquote
L's 12" record
<Ctrl-D>
'L'"'"'s 12" record'
$ echo 'L'"'"'s 12" record'
L's 12" record
从版本20190222,你甚至可以——shellquote多次:
$ parallel --shellquote --shellquote --shellquote
L's 12" record
<Ctrl-D>
'"'"'"'"'"'"'L'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'s 12" record'"'"'"'"'"'"'
$ eval eval echo '"'"'"'"'"'"'L'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'s 12" record'"'"'"'"'"'"'
L's 12" record
它将在所有受支持的shell(不仅仅是bash)中引用该字符串。
这个函数:
quote ()
{
local quoted=${1//\'/\'\\\'\'};
printf "'%s'" "$quoted"
}
允许引用“内部”。像这样使用:
$ quote "urxvt -fg '#111111' -bg '#111111'"
'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
如果要引用的行变得更复杂,比如双引号和单引号混合在一起,那么在变量中获得要引用的字符串可能会变得相当棘手。当出现这种情况时,在脚本中编写需要引用的确切行(类似于此)。
#!/bin/bash
quote ()
{
local quoted=${1//\'/\'\\\'\'};
printf "'%s'" "$quoted"
}
while read line; do
quote "$line"
done <<-\_lines_to_quote_
urxvt -fg '#111111' -bg '#111111'
Louis Theroux's LA Stories
'single quote phrase' "double quote phrase"
_lines_to_quote_
将输出:
'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
'Louis Theroux'\''s LA Stories'
''\''single quote phrase'\'' "double quote phrase"'
所有在单引号内正确引用的字符串。
以下是上面提到的唯一正确答案的详细说明:
有时我会在ssh上使用rsync下载,并且必须转义一个带有'两次!(天啊!)一次用于bash,一次用于ssh。这里也使用了相同的交替引用分隔符原则。
例如,假设我们想要:Louis Theroux的LA Stories……
首先,将Louis Theroux用单引号括起来表示bash,用双引号括起来表示ssh:
“路易泰鲁”的
然后使用单引号转义双引号" "
使用双引号来转义撇号"'"
然后重复#2,使用单引号转义双引号“”
然后将LA Stories包含在bash的单引号中,ssh的双引号中:' ' LA Stories ' '
看哪!你会得到这样的结果:
rsync -ave ssh '"Louis Theroux"''"'"'"'"''"s LA Stories"'
对一个人来说,这是一件可怕的事情——但你明白了吗