Quoting characters in shell scripting

Quoting means putting a string in quotes. By quoting a string, we protect the special characters in the string from reinterpretation or expansion in a shell script.

A special character is a character that has an different interpretation than its liter meaning. The asterisk (*) is a special character, it is a wildcard in globbing and regular expressions. Read more about the wildcards here.

Example of using quotes:

$ ls S*
STARwars STARWARS
$ ls 'S*'
ls: cannot access S*: No such file or directory

Quoting can be done with both (double quotes) ” “ and (single quotes)’ ‘ .

When displaying variable values, it is recommended to enclose their variable names in double quotes. This prevents the reinterpretation of the special characters, except $ , ` (backquote) and  \ (escape).

Use double quotes to prevent word splitting:

$ list="mike jim john"
$ echo "$list"
mike jim john

The command echo $list are invided has 3 arguments, while echo “$list are invited” has only one argumet.

The difference between single quotes and double quotes.
The single quotes are similarry to the double quotes, but within single quotes, every special character except ‘ gets interpreted literally.

Example:

$ A=mike
$ echo "$A"
mike #the double quotes are good
$ echo '$A'
$A #the single quotes are evil

If you liked this, read the next shell scripting article, or browse for the other related articles.

Liked it? Take a second to support Geekster on Patreon!
Tagged with: , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Support LinuxG via Patreon
Support LinuxG.net on Patreon!
Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!