Ends in
00
days
00
hrs
00
mins
00
secs
SHOP NOW

🚀 Extended! 25% OFF All Practice Exams & Video Courses, $2.99 eBooks, Savings on PlayCloud and CodeQuest!

Back to Course

Bash Scripting for Beginners with Hands-On Labs

0% Complete
0/0 Steps

Variables in Bash are used to store values such as text, numbers, or even the result of a command. They allow you to reuse and manipulate data throughout your script. Bash variables are flexible, but there are a few important rules and types to understand: user-declared, environment, local/global scope, and how to perform operations like concatenation or arithmetic.

Bash Variable Examples

1. Declare and use a simple variable:

Bash variables are created by assigning a value with = and used by placing a $ before the variable name.

Bash Scripting Syntax Example
bash
greeting="Hello"
name="John"
echo "$greeting, $name!"

2. Environment Variables

Environment variables are special system-wide variables used to configure the shell or software.

Bash Scripting Syntax Example
bash
echo "Your home directory is: $HOME"

This prints the value of the built-in HOME environment variable. You can also create your own environment variable:

Bash Scripting Syntax Example
bash
export MY_VAR="Visible Everywhere"

3. Local vs. Global Variables

Variables declared inside functions are local by default if specified with local. Otherwise, they are global within the script.

Bash Scripting Syntax Example
bash
myvar="Global"

my_function() {
  local myvar="Local"
  echo "Inside function: $myvar"
}

my_function
echo "Outside function: $myvar"

This shows how local limits the scope of a variable to inside the function.

4. Common Variable Operations

  • Concatenation (Combining Strings)

You can join strings by simply placing them next to each other:

Bash Scripting Syntax Example
bash
first="Bash"
second="Scripting"
echo "$first $second"
  • Arithmetic with Numbers

Use (( )) or let for performing math operations with numeric variables:

Bash Scripting Syntax Example
bash
x=5
y=3
sum=$((x + y))
echo "Sum: $sum"

Or using let:

Bash Scripting Syntax Example
bash
let result=x*y
echo "Multiplication: $result"

Important Points

  • No spaces around the equal sign when assigning variables.
  • Variables are case-sensitive. NAME is different from name.
  • Use export to make a variable available to child processes.
  • Use local inside functions to limit a variable’s scope.

Try It Out!

Create a script that combines two strings into one message. Try to store two numbers and print their product using (( )) too.

Terminal Playground Embed Test

TD Bash PlayCloud

Please click the “Play” button to launch the terminal and wait for it to load. If you’re unable to type, kindly click the refresh button located at the upper right corner.

Skip to content