免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1579 | 回复: 4
打印 上一主题 下一主题

关于双引号的困惑 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-03-23 17:44 |只看该作者 |倒序浏览
脚本A

#!/bin/bash
if [ "${x+X}" = X ]  #if x is set
then
        if [ -n $x ] #if x is not empty
        then
        printf " \$x = %s\n" "$x"
        else
        printf " \$x is set but empty \n"
        fi
else
printf " \$x is not set.\n"
fi


脚本B

#!/bin/bash
if [ "${x+X}" = X ]  #if x is set
then
        if [ -n "$x" ] #if x is not empty
        then
        printf " \$x = %s\n" "$x"
        else
        printf " \$x is set but empty \n"
        fi
else
printf " \$x is not set.\n"
fi


红色部分的不同,造成了脚本的运行错误,不加引号的话,即使变量x为空,打印出来却是$x=     但是加上引号后,当x为空时,可以识别出来为空



但是我想不明白在这里$x 和"$x" 有什么区别,求教大侠!!!

论坛徽章:
0
2 [报告]
发表于 2010-03-23 17:46 |只看该作者
试一下这样:

'"$x"'

论坛徽章:
0
3 [报告]
发表于 2010-03-23 17:49 |只看该作者
'"$x"' 的的结果和$x一样,无法识别空变量

论坛徽章:
5
2015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:50:282015年亚洲杯之朝鲜
日期:2015-03-13 22:47:33IT运维版块每日发帖之星
日期:2016-01-09 06:20:00IT运维版块每周发帖之星
日期:2016-03-07 16:27:44
4 [报告]
发表于 2010-03-23 18:12 |只看该作者
因为word splitting

论坛徽章:
0
5 [报告]
发表于 2010-03-23 18:55 |只看该作者
The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.

The shell treats each character of $IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly "'<space><tab><newline>'", the default, then any sequence of IFS characters serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters "space" and "Tab" are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IF whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs.

Explicit null arguments ("""" or "''") are retained. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained.


Expansion and word splitting
  If no expansion occurs, no splitting is performed.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP