Linux shell单双引号区别

shell单双引号区别:

Shell脚本中很多时候都在用单引号或双引号来框住字符串,但是他们之间是存在区别的
避免踩坑记录…

单引号 ' ' 单引号中的任何字符都没有特殊含义,即一些转义字符,$ 变量引用都会无效,它只把他们当作一个单纯的字符来解释
双引号 " " 双引号类似于单引号,只是它允许 shell 解释美元符号 ( $ )、反引号 ( ` )、反斜杠 ( \ ) 和感叹号 ( ! ), 这些字符与双引号一起使用时具有特殊含义

1.如例,看 $是否生效 :

root@heihei:/# x="123"
root@heihei:/# echo $x
123
root@heihei:/# echo "$x"
123
root@heihei:/# echo '$x'
$x

可以看到单引号内的 x 未生效,直接当作字符串输出了,不加或加双引号的 ‘ x未生效,直接当作字符串输出了,不加或加双引号的` x未生效,直接当作字符串输出了,不加或加双引号的x`则输出的是变量x的值

2.如例,看\是否生效

root@heihei:/# z='\"'
root@heihei:/# echo $z
\"
root@heihei:/# a="\""
root@heihei:/# echo $a
"

可以看到,单引号的时候 \未生效,双引号的时候 \生效了。这个规则对于 换行符\n制表符\t等特定符号不适用

2.1 这类特殊字符如果用echo进行输出,需要echo -e "字符串"才能生效
如例:

root@heihei:/# echo "1\n2"
1\n2
root@heihei:/# echo '1\n2'
1\n2
root@heihei:/# echo -e '1\n2'
1
2
root@heihei:/# echo -e "1\n2"
1
2
root@heihei:/# echo "1\t2"
1\t2
root@heihei:/# echo '1\t2'
1\t2
root@heihei:/# echo -e '1\t2'
1       2
root@heihei:/# echo -e "1\t2"
1       2
root@heihei:/#

3.如例,看反引号(`)是否生效,两个反引号包起来的命令会被优先执行,如

x="`ls`" 
#优先执行ls,再将ls执行结果赋值给x

如下例:

root@heihei:/# x="`ls`"
root@heihei:/# y='`ls`'
root@heihei:/# echo $x
1.txt 2.txt 2.txtn 3.txt
root@heihei:/# echo $y
`ls`
root@heihei:/#

可以看到,双引号内的 反引号是生效的,单引号内的反引号是不生效的

4.如例,看感叹号是否生效

4.1 先提一下感叹号在shell中的一些特别含义:

!! 执行上一条命令
!n 执行history中指定行数的命令(n为行数)
!字符串(字符串长度大于等于1) 执行上一条以字符串为开头的命令

逻辑取反
!= 不等于
![0-9] 除0-9之外

root@heihei:/# ls
1.txt  2.txt  2.txtn  3.txt
#执行上一条命令
root@heihei:/# !!
ls
1.txt  2.txt  2.txtn  3.txt
root@heihei:/# history |tail -n 5
 2002  ls
 2003  history |tail -n 10
 2004  clear
 2005  ls
 2006  history |tail -n 5
 #执行history中指定行数的命令
root@heihei:/# !2003
history |tail -n 10
 1998  history |tail -n 1
 1999  history |tail -n 3
 2000  exit
 2001  cd test/sed
 2002  ls
 2003  history |tail -n 10
 2004  clear
 2005  ls
 2006  history |tail -n 5
 2007  history |tail -n 10
 #执行上一条以his为开头的命令
root@heihei:/# !his
history |tail -n 10
 1998  history |tail -n 1
 1999  history |tail -n 3
 2000  exit
 2001  cd test/sed
 2002  ls
 2003  history |tail -n 10
 2004  clear
 2005  ls
 2006  history |tail -n 5
 2007  history |tail -n 10
root@heihei:/#

再看下当感叹号遇到双引号或单引号时会遇到怎样的化学反应:

root@heihei:/# ls
1.txt  2.txt  2.txtn  3.txt
root@heihei:/# echo "!!"
echo "ls"
ls

如上,先执行了 ls, !!执行结果应该为

root@heihei:/# !!
echo "ls"
ls

效果是有的

root@heihei:/# ls
1.txt  2.txt  2.txtn  3.txt
root@heihei:/# echo '!!'
!!
root@heihei:/#

在看单引号,如上,两个感叹号被当作普通字符串进行了输出

你可能感兴趣的:(Shell,Linux系统,linux,服务器,运维)