为什么在shell脚本中要使用双引号?

3

我理解单引号和双引号的使用。

但我不知道在脚本中什么情况需要用到双引号。

这些语句之间没有区别。

$ echo hello world! $1
$ echo "hello world! $1"

请告诉我普通引号和双引号之间的区别。


在Bash中,单词拆分由“IFS”变量(“内部字段分隔符”)控制,默认值为IFS=$' \t\n'(空格、制表符、换行符)。如果您不引用变量,则单词拆分会在IFS中的任何字符上发生(您可以设置IFS来控制此操作)。引用还将影响文件/路径名扩展 - David C. Rankin
2个回答

5

让我们考虑一个包含以下文件的目录:

$ ls foo*
foo111.txt  foo11.txt  foo1.txt

让我们考虑一下脚本的一个小变化:
$ cat script
#!/bin/sh
echo No quotes $1
echo "Double quotes $1"

现在,让我们运行它:
$ bash script "foo*"
No quotes foo111.txt foo11.txt foo1.txt
Double quotes foo*

正如您所看到的,结果完全不同。没有双引号时,会执行路径名扩展。

为了说明另一个差异:

$ bash script "long              space"
No quotes long space
Double quotes long              space

使用双引号时,单词之间的长空格会被保留。如果没有使用双引号,则所有连续的空格都会被替换为一个空格。这是单词分割的一个示例。


1
一个例子可能演示使用。
  1. To accommodate string with spaces

    var=file name # Not the intended effect.
    

    file is stored in a var and name is taken by shell as a separate cmd which gives you an error.

  2. To prevent word splitting

    var="file name"
    cp $var newfile
    

    Here $var expands to file name and in effect, the command would become

    cp file name newfile
    

    and cp would take file and name as 2 source files and newfile as the destination directory which gives you the error:

    cp: target 'newfile' is not a directory
    

    If there really exists a directory named 'newfile', it will give error:

    cp: cannot stat 'file': No such file or directory
    cp: cannot stat 'name': No such file or directory
    

    The correct method is

    cp "$var" newfile
    

    In this case, the fully expanded $var is considered a single string.


@anishsane:感谢您的编辑。 - sjsam
1
我注意到您回答了许多被关闭为重复的 [tag:bash] 问题。也许您想查看一下 Stack Overflow bash 标签维基,以获取常见问题列表;当然,随时欢迎您帮助我们保持其更新、易懂和有组织性。提前致谢! - tripleee
1
@tripleee:将来我会注意这个的。我承认这次有点懒。 :) - sjsam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接