Why do I use double quotes in shell scripts [duplicate]

醉酒当歌 提交于 2019-12-23 20:29:45

问题


I understand the usage single quote and double quote.

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

there is no diff that statements

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

please show me diff between normal and double quotes.


回答1:


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"

Now, let's run it:

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

To illustrate another difference:

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




回答2:


An example might demonstrate the use

  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.



来源:https://stackoverflow.com/questions/38757649/why-do-i-use-double-quotes-in-shell-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!