Skip to content

LPI Linux Essentials Exam 010-160 - Topic 2.1 - Quoting & Escaping

In Linux, quoting is used to handle strings and variables. It allows you to specify how the shell interprets and processes special characters, variables, and spaces within a string. There are two primary forms of quoting: single quotes (') and double quotes (").

Single Quotes

Single quotes (') are used to create a literal string, which means that everything inside the single quotes is treated as-is, without any interpretation. Here's an example:

echo 'This is a simple string with single quotes.'

In the above command, the string is enclosed in single quotes, and the entire string, including spaces and special characters, is treated as a single entity. It won't expand variables or interpret special characters within it.

Double Quotes

Double quotes (") are used to create a string where variables and some special characters are expanded or interpreted. Here's an example:

name="John"
echo "Hello, $name!"

In this case, the value of the variable $name is expanded within the double quotes, so the output will be "Hello, John!". Double quotes allow you to include variable values and interpret backslashes for certain characters.

Escaping Variables

Sometimes, you may want to include a variable within a string, but you don't want it to be expanded. To do this, you can escape the variable using a backslash (\). This ensures that the variable is treated as a literal string rather than being replaced with its value. Here's an example:

name="John"
echo "His name is \$name."

In the above command, the variable $name is preceded by a backslash, which means it won't be expanded. The output will be "His name is $name."

Exercises

Below are some exercises to illustrate the use of single quotes, double quotes, and escaping variables:

Exercise: Using single quotes:

Set the variable and run the command to see what gets displayed on screen:

var='apple and pears'
echo 'This is a single-quoted string. It will not expand $variables.'

The output will be:

This is a single-quoted string. It will not expand $variables.

Exercise: Using double quotes:

Set the variable and run the command to see what gets displayed on screen:

var='apple and pears'
echo "This is a double-quoted string. It will expand $var."

The output will be:

This is a double-quoted string. It will expand apple and pears.

Exercise: Escaping variables

Set the variable and run the command to see what gets displayed on screen:

var='apple and pears'
echo "I have escaped variable \$var."

The output will be:

I have escaped variable $var.