Using Variables in Shell Scripts

Introduction to Using Variables in Shell Scripts

Welcome back to the world of shell scripting. In the previous lesson, you crafted your very first shell script that printed "Hello, World!" to the screen. Today, we will take the next step by exploring how to use variables in shell scripts. This lesson will introduce you to variable declaration, reassignment, and some basic arithmetic operations.

Using variables can make your scripts more dynamic and flexible, allowing you to store information, reuse values, and perform calculations. Let's get started!

Creating and Using Variables

Variables in shell scripts are used to store data that can be reused throughout the script. To define a variable in a shell script, you use the syntax:

text
variable_name=value

An important distinction of bash is there cannot be spaces before or after the = sign.

To access the value of a variable, use a $ before the variable name.

Let's take a look at an example:

Shell
#!/bin/bash

greeting="Hello"
name="World"
echo "$greeting, $name!"  # Prints: Hello, World!
  • greeting="Hello": This line creates a variable named greeting and sets its value to "Hello."
  • name="World": Another variable named name is created and assigned the value "World."
  • echo "$greeting, $name!": This command prints the variables greeting and name with a comma and exclamation mark. The output will be: Hello, World!

Variables are essential for making your scripts more modular and easier to maintain. The values can be changed without modifying the entire script.

Variable Reassignment

Variables in shell scripts can be reassigned new values, making them adaptable to different scenarios. Let’s see how variable reassignment works:

Shell
#!/bin/bash

greeting="Hello"
hello=$greeting
echo $hello  # Prints: Hello
  • hello=$greeting: This line assigns the value of the variable greeting to the variable hello. The $ is required to access the value stored in the greeting variable
  • echo $hello: This prints the value of hello, which is now "Hello."

With variable reassignment, you can easily propagate changes throughout your script by modifying a single value.

Defining and Using Integers

Shell scripts also allow you use arithmetic operations such as +, -, *, /, and %. Variables used in arithmetic operations must be preceded by $. The $(()) syntax is used to evaluate the arithmetic expression within the parentheses. Let's take a look:

Shell
#!/bin/bash

# Defining integers
num1=2
num2=5

# Performing addition 
sum=$(($num1 + $num2))
echo $sum  # Prints: 7
  • num1=2 and num2=5: These lines create two integer variables, num1 and num2.
  • sum=$(($num1 + $num2)): This line access num1 and num2 using $. The arithmetic expression is inside $(()) to correctly evaluate the expression.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal