ILD

bash单引号中包含单引号
作者:Herbert Yuan 邮箱:yuanjp@hust.edu.cn
发布时间:2018-1-18 站点:Inside Linux Development

不允许在单引号中包含单引号,即使转义单引号也不行:

1
2
echo '\''
>


但是用Bash的字符拼接特性可以实现:

1
2
echo ''"'"''
'


上述实际上,是3个部分拼接

'  '

" ' "

' '

中间没有空格,为了显示添加的空格,第一个是空字符串,第二个是单引号,第三个是空字符串。

Explanation of how '"'"' is interpreted as just ':

  1. ' End first quotation which uses single quotes.

  2. " Start second quotation, using double-quotes.

  3. ' Quoted character.

  4. " End second quotation, using double-quotes.

  5. ' Start third quotation, using single quotes.

If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word.


实际应用:

1
2
echo 'Jim'"'"'s'
Jim's


但是通常使用双引号是可以的,具体要根据强引用和弱引用的作用范围来确定。

1
2
echo "Jim's"
Jim's


参考

https://stackoverflow.com/questions/1250079/how-to-escape-single-quotes-within-single-quoted-strings


Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.