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
NB - Strings must be inside quotes (" ").
NB - 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"
NB - 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
- Script 2
- 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
NB - 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!
Top comments (0)