问题
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
To accommodate string with spaces
var=file name # Not the intended effect.fileis stored in avarandnameis taken by shell as a separate cmd which gives you an error.To prevent word splitting
var="file name" cp $var newfileHere $var expands to
file nameand in effect, the command would becomecp file name newfileand cp would take
fileandnameas 2 source files andnewfileas the destination directory which gives you the error:cp: target 'newfile' is not a directoryIf 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 directoryThe correct method is
cp "$var" newfileIn this case, the fully expanded
$varis considered a single string.
来源:https://stackoverflow.com/questions/38757649/why-do-i-use-double-quotes-in-shell-scripts