Variables in Bash Scripting: A Beginner’s Guide
As a newbie to the world of Linux and scripting, understanding the concept of variables in Bash scripting can be both essential and intriguing. Variables play a fundamental role in storing and manipulating data within a script, allowing you to create dynamic and interactive scripts. Always use variables in the script to make your life easier. In this article, we’ll learn the basics of variables in Bash scripting, how to declare the variable in Bash scripting and use it, and interactive examples with commands to help you grasp the concept effectively.
If you are new to bash script read: How to write your first bash script
What are Variables in Bash Scripting?
In any programming, a variable is a symbolic name or identifier that represents a value or data stored in the computer’s or server’s memory. Variables act as containers that hold different types of information, such as numbers, text, filenames, and more. In Bash scripting, variables enable you to store values temporarily in memory and reference them throughout your script and you can use the same multiple times because Bash is dynamically typed, making it easier to work with data dynamically.
Declaring Variables in Bash
In Bash, declaring a variable is as simple as assigning a value to it with a “=” sign. There are no data types required when declaring a variable; Bash automatically determines the type based on the context. To declare a variable in bash, use the below syntax:
variable_name=value
For example, to store the value “Hello, Explinux!” in a variable called as below example :
greeting="Hello, Explinux!"
Remember that there should be no spaces around the equal sign when declaring a variable in Bash scripting. For string use “” and number you can use 1 or any number without “”.
Using Variables in Bash
Once we have declared a variable, you can use it throughout your script by referencing its name with a dollar sign ($
). For example, to print the value of the greeting
variable which we have declared before, you can use the echo
command:
greeting="Hello, Explinux!"
echo $greeting
The output of the script will be when you run it :
Hello Explinux!
Using the dollar sign ($
) before the variable name in the script tells Bash to substitute the variable with its value during execution.
Commands with Variables
Variables in Bash are not limited to static values; they can also hold the output of commands and that is useful to write automation scripts. By enclosing the Linux command in backticks (`
) or using the $()
syntax, you can capture the command’s output and store it in a variable.
Example: Command Output in a Variable
#!/bin/bash
# Command Output in a Variable
# Store the current date in a variable using backticks
current_date=`date`
# Print the value of the variable
echo "Current Date: $current_date"
In this above example, the date
command retrieves the current date, and we store the output in the current_date
variable. The echo
command then displays the value of the current_date
variable in the terminal, showing the current date when the script is run.
Example: Command Output in a Variable with $()
#!/bin/bash
# Command Output using $() in a Variable.
# Store the output of the 'ls' command in a variable using $()
files=$(ls)
# Print the value of the variable
echo "Files in the current directory: $files"
Here, the ls
command lists the files in the current directory where the script is executed. We use the $()
syntax to capture the output of the ls
command and store it in the files
variable. The echo
command then displays the stored value of the files
variable, after execution, it will show the list of files in the directory.
Rules for Naming Variables
When naming variables in Bash scripting, you need to follow certain rules to define variables:
- Variable names must begin with an alphabetic letter (a-z or A-Z) or an underscore (_).
- After the first character, variable names can also include digits (0-9).
- No spaces are allowed in variable names in the bash script.
- Variable names are case-sensitive. For example,
greeting
andGreeting
are considered two different variables. This is due to Linux also case sensitive.
Arithmetic with Variables
Performing arithmetic operations in Bash scripting is a good example to learn variables. Let’s see an example of how to use variables for arithmetic:
#!/bin/bash
# Arithmetic with Variables
# Declare two variables
num1=10
num2=5
# Perform arithmetic operations
sum=$((num1 + num2))
difference=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))
# Print the results
echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Quotient: $quotient"
In this example, we declare two variables num1
and num2
and perform various arithmetic operations (addition, subtraction, multiplication, and division) using these two variables. The output will be using the echo
command, demonstrating how variables can store and manipulate data in Bash script.
Accepting User Input as Variable
Variables are also useful for accepting user input and processing or manipulating it in the script. Let’s see below a simple script example that takes the user’s name as input and greets them:
#!/bin/bash
# Accept User Input and Greet
# Ask the user for their name
read -p "Enter your name: " name
# Greet the user with variable name($name)
echo "Hello, $name! Nice to meet you."
In this script, we use the read
command to prompt the user for their name and store the input in the name
variable. The entered name by the user is then used in the greeting message when the script is executed. This is just an example you can use commands as well or any other input.
Conclusion
Variables are the building blocks of Bash scripting, enabling you to store, manipulate, and interact with data dynamically. With the knowledge of how to declare and use variables, you can create more flexible and powerful Bash scripts. Remember the basic syntax for declaring variables, use the dollar sign ($
) to reference their values, and follow the rules for naming variables.
As you continue your journey into the world of Bash scripting, the understanding of variables will become more crucial as you explore advanced concepts like loops, conditionals, and functions. Practice creating scripts that utilize variables in various scenarios, and you’ll soon gain confidence in your ability to develop efficient and functional Bash scripts to automate tasks and enhance your productivity. Happy scripting