Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 69

Scripting Essentials: Variables, Substitution, and Quoting

Recommended resources

Hello! Welcome back to your training for the CompTIA Linux+ exam.

In our last lesson, we took the first crucial step into shell scripting by learning how to write a basic script, add the essential #!/bin/bash shebang, and make it executable with chmod. You now know how to create a simple, static list of commands that the system can run for you.

Today, we'll build on that foundation to make your scripts dynamic and intelligent. This lesson addresses the learning outcome: Use variables, command substitution, and quoting in scripts. We will explore how to store and reuse information with variables, how to capture the output of commands in real-time, and how to use quotes to handle text and special characters safely. These are the core components that elevate a script from a simple checklist to a powerful automation tool.

1. Storing Information with Variables

The first step to making a script dynamic is giving it a way to store and manage data. In scripting, we do this using variables. Think of a variable as a labeled container where you can put a piece of information, like a username, a filename, or a number, and then refer to it by its label later.

a) Declaring and Referencing Variables

Let's watch a video that introduces the fundamental syntax for working with variables.

How To Write Bash Scripts In Linux - Complete Guide (Part 3 - Variables)

This segment from the 'How To Write Bash Scripts' series by Learn Linux TV clearly explains how to create (declare) a variable and how to access (reference) its value. Pay close attention to the syntax, especially the use of the = for assignment and the $ for referencing.

Watch the section from 00:54 to 05:31. Focus on the distinction between assigning a value to a variable (e.g., my_name='Jay') and retrieving that value (e.g., echo $my_name).

As the video demonstrated, there are two key rules:

  1. To assign a value: Use the format variable_name=value. It is critical that there are no spaces on either side of the = sign.
  2. To read a value: Prefix the variable name with a dollar sign ($), like $variable_name. The $ tells the shell to substitute the variable's name with its stored value.

For example:

# Assignment (no spaces around =)
server_name="web-01"

# Referencing (with $)
echo "Connecting to server: $server_name"

b) Variable Naming Conventions and Scope

A good practice is to name your variables in a way that makes their purpose clear. In bash scripting, there's a helpful convention:

  • lowercase_with_underscores: Use this for variables you create inside your own scripts (e.g., file_path, user_count).
  • ALL_CAPS: This is reserved for environment variables, which are system-wide variables that are always available, like $USER (your username) or $HOME (your home directory path).

Following this convention prevents you from accidentally overwriting an important system variable and makes your scripts easier for others to read.

To learn more about this and see why variables are so useful, please watch two more clips from the same video.

How To Write Bash Scripts In Linux - Complete Guide (Part 3 - Variables)

These next two segments explain the practical benefit of using variables and introduce the concept of pre-existing environment variables.

First, watch from 11:10 to 14:09 to see how variables help you avoid repetition and make scripts easier to maintain. Then, watch from 19:15 to 23:07 to understand what environment variables are (like $USER) and why the uppercase/lowercase naming convention is important.

Test your understanding!

You want to create a script that greets the currently logged-in user. You write the following script:

#!/bin/bash
current_user=USER
echo "Hello, current_user"

When you run it, the output is Hello, current_user. What are the two mistakes in this script, and how would you correct them to get the desired output (e.g., Hello, your_username)?

Show answer
  1. Mistake 1: The variable assignment current_user=USER assigns the literal string "USER", not the value of the environment variable. It should be current_user=$USER to read the value from $USER.
  2. Mistake 2: The echo command uses single quotes in the final version shown in the solution which would prevent variable expansion. The string echo "Hello, current_user" will print the literal text. It should use double quotes: echo "Hello, $current_user" to allow the variable $current_user to be expanded to its value.

Corrected script:

#!/bin/bash
current_user=$USER
echo "Hello, $current_user"

Or, more simply, you could use the environment variable directly:

#!/bin/bash
echo "Hello, $USER"

2. Controlling Expansion with Quoting

You may have noticed the different uses of single (') and double (") quotes. Their behavior is one of the most important concepts in shell scripting for preventing errors.

  • Single Quotes ('...'): Preserve the literal value of every character. Nothing is substituted. $USER inside single quotes is treated as the four characters $, U, S, E, R.
  • Double Quotes ("..."): Allow for substitution (or expansion). The shell will replace variables ($variable) and a few other special characters with their values. This is what you usually want when you're working with variables.

This distinction is crucial when your variables contain spaces or special characters.

Let's see a direct comparison.

How To Write Bash Scripts In Linux - Complete Guide (Part 3 - Variables)

This video clip from Learn Linux TV provides a perfect illustration of the difference between single and double quotes. It shows how the same echo command produces completely different results based on the quotes used.

Watch the segment from 08:09 to 11:10. Focus on why the output changes when the script is modified from using double quotes to single quotes.

Best Practice: When in doubt, enclose your variables in double quotes ("$variable"). This prevents the shell from splitting the variable's value if it contains spaces and ensures predictable behavior.

For example, if filename="my report.docx", then rm "$filename" will correctly delete the single file named "my report.docx". Without quotes, rm $filename would try to delete two separate files: "my" and "report.docx".


3. Capturing Output with Command Substitution

Variables are great for storing static text, but what if you need to store information that changes, like the current date, the system's IP address, or a list of files? For this, we use command substitution.

Command substitution allows you to run a command and "capture" its output, which you can then use as part of another command or assign to a variable.

The modern and recommended syntax is $(command).

For instance, to store the current date and time in a variable, you would write:

now=$(date)
echo "The report was generated at: $now"

The shell first executes the date command inside the $() and then substitutes the entire $(date) expression with the command's output.

The following video and image illustrate this powerful feature.

How To Write Bash Scripts In Linux - Complete Guide (Part 3 - Variables)

This section of the Learn Linux TV video demonstrates how to capture the output from commands like ls, pwd, and date and store it in a variable.

Watch from 14:09 to 18:36. Notice how the output of a command is assigned to a variable using the var=$(command) syntax.

Demonstration of Command Substitution in a Linux Terminal
This image shows the entire workflow: a script is written using command substitution (likely `files=$(ls)`), made executable, and then run. The output on the terminal is the result of the `ls` command, demonstrating that the command inside the script was successfully executed and its output printed.

A common use case is creating dynamically named files, like a daily backup.

# Create a backup archive with today's date in the filename.
# The +%F option for date formats it as YYYY-MM-DD.
tar -czf "backup-$(date +%F).tar.gz" /var/www

If you run this today, it might create a file named backup-2023-10-27.tar.gz. Run it tomorrow, and the filename will be different. This is the power of dynamic scripting.

Test your understanding!

Write a single line for a script that creates a variable named file_count and stores the number of files and directories in the current directory within it. (Hint: The ls command lists files, and the wc -l command counts lines).

Show answer

The line should pipe the output of ls to wc -l and use command substitution to capture the result:

file_count=$(ls | wc -l)

When you later use echo "$file_count", it will print the number of items found by ls.


Conclusion

You've now learned the three fundamental techniques for making scripts flexible and powerful. These concepts are used in nearly every non-trivial shell script.

Key Takeaways:

  • Variables store data using the name=value syntax and are retrieved with $name. Use lowercase for your script variables.
  • Quoting is essential for controlling how the shell interprets text. Double quotes (") allow variable and command substitution, while single quotes (') treat everything as a literal string.
  • Command Substitution $(...) lets you execute a command and use its output within another command or assign it to a variable, making your scripts dynamic.

Preview of the Next Lesson:

With the ability to store and manage data, the next logical step is to make your scripts perform actions based on that data. In the next lesson, we will "Implement conditional statements (if/then/else) and loops (for, while) in scripts." This will unlock the ability to add decision-making logic and perform repetitive actions, transforming your scripts into true programs.