bash中单引号和双引号的坑

本文详细解析了Bash shell中单引号、双引号和反引号在字符串中的行为差异,包括变量替换、转义字符、特殊字符处理等,并列举了15个实例以说明其实际效果。理解这些差异有助于提高Shell脚本的编写效率。
摘要由CSDN通过智能技术生成

假如有以下环境

a=apple      # 一个变量
arr=(apple)  # 一个只有一个元素的数组

然后使用echo来打印第二列的表达式,然后会出现第三列的结果,原因是第四列

#表达式结果原因
1"$a"apple""之间的变量会被替换为变量的值,因为$表示一个变量
2'$a'$a‘’之间的变量不会被替换为变量的值
3"'$a'"'apple'""中如果包含了'' ,那么‘’会失去他的作用,没有任何意义,只是单纯的符号,但是变量依然会被替换成值。
4'"$a"'"$a"''中如果包含了"" ,那么""会失去他的作用,没有任何意义,只是单纯的符号。
5'\''invalidcan not escape a ' within ''; use "'" or $'\'' (ANSI-C quoting)
6"red$arocks"red$arocks does not expand $a; use ${a}rocks to preserve $a
7"redapple$"redapple$$ followed by no variable name evaluates to $
8'\"'\"\ has no special meaning inside ''
9"\'"\'shell程序认为,\'"" 之中没有意义所以不会被转义
10"\"""\" is interpreted inside ""
11"*"*glob does not work inside "" or ''
12"\t\n"\t\n\t and \n have no special meaning inside "" or ''; use ANSI-C quoting
13"`echo hi`"hi`` and $() are evaluated inside "" (backquotes are retained in actual output)
14'`echo hi`'echo hi`` and $() are not evaluated inside '' (backquotes are retained in actual output)
15'${arr[0]}'${arr[0]}array access not possible inside ''
16"${arr[0]}"applearray access works inside ""
17$'$a\''$a'single quotes can be escaped inside ANSI-C quoting
18"$'\t'"$'\t'ANSI-C quoting is not interpreted inside ""
19'!cmd'!cmdhistory expansion character '!' is ignored inside ''
20"!cmd"cmd argsexpands to the most recent command matching "cmd"
21$'!cmd'!cmdhistory expansion character '!' is ignored inside ANSI-C quotes

来源:https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值