Working with Shell Variables

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to work with shell variables. Shell variables are used to store data in shell scripts, and they can hold various types of values such as numbers, characters, or strings. Shell variables are created by assigning a value to them using the = sign.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) linux(("`Linux`")) -.-> linux/SystemInformationandMonitoringGroup(["`System Information and Monitoring`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/BasicFileOperationsGroup -.-> linux/ls("`Content Listing`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") linux/SystemInformationandMonitoringGroup -.-> linux/date("`Date/Time Displaying`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/VariableHandlingGroup -.-> shell/str_manipulation("`String Manipulation`") shell/VariableHandlingGroup -.-> shell/param_expansion("`Parameter Expansion`") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("`Command Substitution`") shell/AdvancedScriptingConceptsGroup -.-> shell/subshells("`Subshells and Command Groups`") subgraph Lab Skills linux/echo -.-> lab-153894{{"`Working with Shell Variables`"}} linux/cd -.-> lab-153894{{"`Working with Shell Variables`"}} linux/ls -.-> lab-153894{{"`Working with Shell Variables`"}} linux/chmod -.-> lab-153894{{"`Working with Shell Variables`"}} linux/date -.-> lab-153894{{"`Working with Shell Variables`"}} shell/shebang -.-> lab-153894{{"`Working with Shell Variables`"}} shell/comments -.-> lab-153894{{"`Working with Shell Variables`"}} shell/quoting -.-> lab-153894{{"`Working with Shell Variables`"}} shell/variables_decl -.-> lab-153894{{"`Working with Shell Variables`"}} shell/variables_usage -.-> lab-153894{{"`Working with Shell Variables`"}} shell/str_manipulation -.-> lab-153894{{"`Working with Shell Variables`"}} shell/param_expansion -.-> lab-153894{{"`Working with Shell Variables`"}} shell/cmd_substitution -.-> lab-153894{{"`Working with Shell Variables`"}} shell/subshells -.-> lab-153894{{"`Working with Shell Variables`"}} end

Creating Shell Variables

To create a shell variable, you need to assign a value to it. The variable name is case sensitive and can consist of letters and the underscore "_". No space is permitted on either side of the = sign when initializing variables.

Let's create a file named ~/project/variables.sh and add the following content:

PRICE_PER_APPLE=5
MyFirstLetters=ABC
greeting='Hello        world!'

Referencing Shell Variables

To reference a shell variable, you can simply use its name. However, there are a few scenarios where you need to use special syntax.

Escaping Special Characters

If you want to include special characters in a variable's value, you need to escape them using a backslash "\".

PRICE_PER_APPLE=5
echo "The price of an Apple today is: \$HK $PRICE_PER_APPLE"

Avoiding Ambiguity

To avoid any ambiguity in variable substitution, you can enclose the variable name with {}.

MyFirstLetters=ABC
echo "The first 10 letters in the alphabet are: ${MyFirstLetters}DEFGHIJ"

Preserving Whitespace

If the variable value contains whitespace, you can preserve it by enclosing the variable name with "".

greeting='Hello        world!'
echo $greeting" now with spaces: $greeting"

Run the script and you will see the following output:

cd ~/project
chmod +x variables.sh
./variables.sh
The price of an Apple today is: $HK 5
The first 10 letters in the alphabet are: ABCDEFGHIJ
Hello world! now with spaces: Hello        world!

Command Substitution

You can assign a variable with the value of a command output using command substitution. Command substitution can be done by enclosing the command with ``(back-ticks) or $().

FILELIST=$(ls)
FileWithTimeStamp=/tmp/file_$(/bin/date +%Y-%m-%d).txt

echo "FileWithTimeStamp = $FileWithTimeStamp"
echo "FILELIST = $FILELIST"

Note that when the script runs, it will execute the command inside the $() parenthesis and capture its output.

./variables.sh
FileWithTimeStamp = /tmp/file_2023-09-01.txt
FILELIST = variables.sh

Exercise

In this exercise, you need to create a string, an integer, and a complex variable using command substitution.

  • The string should be named BIRTHDATE and should contain the text "Jan 1, 2000".
  • The integer should be named Presents and should contain the number 10.
  • The complex variable should be named BIRTHDAY and should contain the full weekday name of the day matching the date in variable BIRTHDATE.

You can use the date command to convert a date format into a different date format. For example, to convert a date value date1 to the day of the week of date1, use the following command:

date -d "$date1" +%A

Note: The -d option is used to specify the date to be converted. The +%A option is used to specify the output format.

Tasks

  • Modify the ~/project/birthdate.sh script to create the variables as described above.

Results

  • Run the script and verify the output.
cd ~/project
chmod +x birthdate.sh
./birthdate.sh
Jan 1, 2000
10
Saturday

Summary

In this lab, you learned how to work with shell variables. You learned how to create shell variables and how to reference them. You also learned about command substitution and how to assign a variable with the output of a command. Keep practicing and exploring different scenarios to enhance your shell scripting skills.

Other Shell Tutorials you may like