我理解单引号和双引号的使用。
但我不知道在脚本中什么情况需要用到双引号。
这些语句之间没有区别。
$ echo hello world! $1
$ echo "hello world! $1"
请告诉我普通引号和双引号之间的区别。
让我们考虑一个包含以下文件的目录:
$ 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
使用双引号时,单词之间的长空格会被保留。如果没有使用双引号,则所有连续的空格都会被替换为一个空格。这是单词分割的一个示例。
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.
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.
bash
标签维基,以获取常见问题列表;当然,随时欢迎您帮助我们保持其更新、易懂和有组织性。提前致谢! - tripleee
IFS=$' \t\n'
(空格、制表符、换行符)。如果您不引用变量,则单词拆分会在IFS
中的任何字符上发生(您可以设置IFS
来控制此操作)。引用还将影响文件/路径名扩展。 - David C. Rankin