为什么我在 shell 脚本中使用双引号 [英] Why do I use double quotes in shell scripts

查看:69
本文介绍了为什么我在 shell 脚本中使用双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解单引号和双引号的用法.

I understand the usage single quote and double quote.

但我不知道脚本中需要双引号的情况.

but I don't know situation need to double quotes in the script.

没有区别声明

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

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

please show me diff between normal and double quotes.

推荐答案

让我们考虑一个包含这些文件的目录:

Let's consider a directory with these files:

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

让我们考虑对您的脚本稍作改动:

Let's consider a minor variation on your script:

$ 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*

如您所见,结果完全不同.如果没有双引号,则执行路径名扩展.

As you can see, the results are completely different. Without the double quotes, pathname expansion is performed.

为了说明另一个区别:

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

使用双引号,单词之间的长空格被保留.没有它,所有连续的空白都会被一个空白替换.这是一个分词的例子.

With double quotes, the long space between words is preserved. Without it, all contiguous whitespace is replaced with a single blank. This is an example of word splitting.

这篇关于为什么我在 shell 脚本中使用双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆