backslash preceding characters

本文详细解释了Shell中转义字符的处理方式,包括在不同上下文中(如普通字符串、双引号内、heredoc等)如何被解析。特别关注了如何使用反斜杠来转义特殊字符,并对比了命令替换符号`...`与$(...)的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In regular, unquoted situations, every character with a backslash preceding it has it's backslash processed, whether it needs it or not.

But inside quotes or a heredoc, only the few listed characters are treated specially. Backslashes preceding all other regular characters will remain literal.

command + # output + # explanation:
Code:
echo \z     # z         #backslash interpreted.
echo \\z    # \z        #2 backlashes become one.
echo "\z"   # \z        #backslash not intepreted, not preceding a special character
echo "\\z"  # \z        #2 backslashes become one. "\" precedes a special character, another '\'.
A heredoc does not process quotemarks, but it does process " $" and " `", so substitutions still happen. It also processes backslashes if they are in front of the reserved characters, allowing you to escape them if needed. All other characters are ignored just as in the quoted situation above.

Code:
foo=bar

cat <<EOF
\z
\\z
"\z"
"\\z"
echo $foo
echo \$foo
$( echo $foo )
$( echo \$foo )
EOF

#output:
\z
\z
"\z"
"\z"
echo bar
echo $foo
bar
$foo
Note that if the delimiting word (the opening EOF) is quoted or backslashed, it won't process anything. The entire text will become literal.

As for this:
Code:
$ var=test
$ echo `echo \$var`
test
The way `..` processes backslashes appears to be rather confusing overall. See here. It appears to be doing some kind of double-expansion, in fact.

$(..), on the other hand, simply processes everything it contains as a regular command subshell. Just another reason not to use backticks!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值