您的位置:首页 > 运维架构 > Shell

shell中单引号和双引号区别

2015-08-13 00:04 435 查看
1. shell脚本中的单引号和双引号一样都是字符串的界定符,而不是字符的界定符。单引号用于保持引号内所有字符的字面值,即使引号内的\和回车也不例外,但是字符串中不能出现单引号。(注意是所有,只是单引号本身不能够出现在其中)。 双引号用于保持引号内所有字符的字面值(回车也不例外),但以下情况除外:$加变量名可以取变量的值
反引号仍表示命令替换
\$表示$的字面值
\`表示`的字面值
\"表示"的字面值
\\表示\的字面值
除以上情况之外,在其它字符前面的\无特殊含义,只表示字面值
[lxh@test1 ~]$ echo "`date`"
2015年 08月 13日 星期四 00:00:16 CST
[lxh@test1 ~]$
[lxh@test1 ~]$ echo '`date`'
`date`
[lxh@test1 ~]$ echo "$(date)"
2015年 08月 13日 星期四 23:16:50 CST
[lxh@test1 ~]$ echo '$(date)'
$(date)

[lxh@test1 ~]$ str="today is Monday"
[lxh@test1 ~]$ echo "\\\$$str"
\$today is Monday
[lxh@test1 ~]$ echo "\\$str$"
\today is Monday$
[lxh@test1 ~]$ echo "\"$str"
"today is Monday
可见,单引号中完全是保持字符串的原型输出,而双引号进行了命令替换。
[lxh@test1 ~]$ echo '$HOME'
$HOME
[lxh@test1 ~]$
[lxh@test1 ~]$
[lxh@test1 ~]$ echo "$HOME"
/home/lxh


2.单引号、双引号用于用户把带有空格的字符串赋值给变量事的分界符。
  [root@localhost sh]# str="Today is Monday"
  [root@localhost sh]# echo $str
  Today is Monday
  如果没有单引号或双引号,shell会把空格后的字符串解释为命令。
  [root@localhost sh]# str=Today is Monday
  bash: is: command not found
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: