This content originally appeared on DEV Community and was authored by Babs
LearnBashScriptingWithMe
Day 2 β Variables
“In case youβd like to revisit or catch up on what we covered on Day One, hereβs the link:
https://dev.to/babsarena/learn-bash-scripting-with-me-day-1-1ekd
Variables in Bash scripting are used to store data, such as numbers, text, or file paths. They are a way to label and reference information that can be used later in a script.
We begin by creating a file using any text editor of our choice and naming it variables.sh.
Declaring the Shell
At the very top of the script, specify the shell you want to use:
#!/bin/bash
- Creating a Variable Letβs create a variable called NAME.
Best Practice:
Variable names in Bash are usually written in capital (block) letters.
Using lowercase will still work, but uppercase is the recommended convention.
Important Rules When Declaring Variables
– No spaces before or after the = sign, otherwise the script will fail.
NAME = “Babs” Invalid
NAME=”Babs” Valid
– Strings must be inside quotes (” “).
Numbers donβt need quotes.
AGE=25 Valid
CITY=”Nairobi” Valid
- Using Variables
To call a variable, use the dollar sign ($):
echo "My name is $NAME"
You can also use curly braces {} when combining variables with text:
SPORT=”Foot”
echo “The most popular sport is ${SPORT}ball”
Output: The most popular sport is Football
Pictorial Examples of the script and the outcome
Outcome:
Script 2
Outcome:
- Naming Rules
Variable names must start with an alphabet (AβZ or aβz).
They cannot start with a number.
01_NAME=”Test” # Invalid
NAME_01=”Test” # Valid
SPORT_07=”Test” # Valid
If variables are not properly declared, the script will return an error.
Things to Keep in Mind
- If your script fails to run, ensure that the file is executable.
You can check this with:
ls -la
- If itβs not executable, make it executable with:
chmod +x variables.sh
- Always enclose string variables in quotation marks (” “).
Missing quotes may cause your script to fail.
And thatβs the foundation of working with variables in Bash scripting for day 2!
This content originally appeared on DEV Community and was authored by Babs