Here is the video version, if you prefer it:
Today let’s talk about quoting and string literals.
First, let’s take a trip back down the memory lane and look at what happens when you press Enter and thus signal the shell to run a command: (Ward, 2014)
- Before running the command, the shell performs substitutions on variables and globs
- The shell passes the results of the substitutions to the command
To illustrate this, here is an example:
anaconda3 grep-hadoop-example Public TUTORIAL
'Calibre Library' hadoop-example Python-3.7.4 TUTORIAL~
Desktop Linux_folder snap Untitled.ipynb
Documents Music stanfordnlp_resources Videos
Downloads Pictures Templates
mislav@mislavovo-racunalo:~$ echo A*
mislav@mislavovo-racunalo:~$ echo a*
mislav@mislavovo-racunalo:~$ echo C*
Let’s remember what happens here: In the first command,
A* gets printed out because there is not folder starting with capital a. Then, for echo
a*, we get
anaconda3, because there is a folder starting with zero or more lowercase a’s – that is
anaconda3. Same for
Calibre Library, only it starts with capital c.
But get this now:
mislav@mislavovo-racunalo:~$ echo "a*"
So double quotes prevent globbing. However, double quotes don’t prevent variables from expanding:
mislav@mislavovo-racunalo:~$ echo "$PATH"
Single quotes prevent both globbing and variables from expanding:
mislav@mislavovo-racunalo:~$ echo 'a*'
mislav@mislavovo-racunalo:~$ echo '$PATH'
So thus I propose a rule-of-thumb: In shell scripts, always use single quotes unless you have a strong reason not to do so. This is to prevent unintended globbing or variable expansion.
A sidenote: If you ever find yourself in a situation where you need to escape single quotes within a single-quoted string, see (“How to escape single quotes within single quoted strings,” n.d.).
We haven’t added anything to our tutorial script. I will tell you explicitly when to add something, so don’t worry.
Hope you learned something useful!
How to escape single quotes within single quoted strings. (n.d.). Retrieved February 21, 2020, from https://stackoverflow.com/questions/1250079/how-to-escape-single-quotes-within-single-quoted-strings/16605140#16605140
Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 251-253