I'm a new engineer who has just started writing bash. I'm coding ** "Oh, here single quote? Double? Is it necessary to surround it in the first place? Well, it doesn't matter if it moves ..." ** I'm always worried about that, so I decided to organize it again.
OK with the following recognition. Details will be explained individually later.
If you enclose a string in single quotes, every character in the string loses its special meaning and is interpreted as its literal meaning.
# $HOME is a special shell variable that sets the home directory of the user running the shell
$ echo '$HOME' #Surround with single quotes
$HOME #As it is$Output as HOME
$ echo "$HOME" #Enclose in double quotes
/c/Users/guest.name #Expands to the value of a shell variable
$ echo '*' #Surround with single quotes
* #As it is*Is output
$ echo * #Do not quote anything
bin doc src #Expanded to the file name in the current directory
If you enclose a string in double quotes, most characters lose their special meaning, much like single quotes. However, the special meanings of \ $ and `remain, so parameter expansion and command substitution are done. ** To prevent unexpected behavior, it seems better to enclose "\ $ variables" and "\ $ (command replacement)" in double quotes. ** **
#Parameter expansion
$ var='*** hello world ***' #With a series of spaces*String containing
$ echo "$var" #Enclose in double quotes
*** hello world *** #Displayed correctly
$ echo $var #Do not enclose in double quotes
bin doc src hello world bin doc src #Spaces are interpreted as delimiters and the filenames of the current directory are expanded before and after
#Command replacement
$ user='$(whoami)' #Surround with single quotes
$ echo "$user"
$(whoami) #Interpreted as just a string
$ user="$(whoami)" #Enclose in double quotes
$ echo "$user"
guest.name #The result of the whoami command is assigned
If you put a backslash in front of a character, the one character immediately after the \ loses its special meaning and is interpreted as the literal meaning.
$ echo \$HOME # $Put a backslash in front of
$HOME #As it is$Output as HOME
$ echo $HOME #I have to add a backslash
/c/Users/guest.name #Expands to the value of a shell variable
$ echo \* # *Put a backslash in front of
* #As it is*Is output
$ echo * #I have to add a backslash
bin doc src #Expanded to the file name in the current directory
References: Takenori Yamamori "[Revised 3rd Edition] Shell Script Basic Reference ── #! / Bin / sh can do this" Technical Review Company (2018/11/14)
Recommended Posts