Learn Bash Scripting With Me πŸš€ – Day 2



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.

  1. We begin by creating a file using any text editor of our choice and naming it variables.sh.

  2. Declaring the Shell
    At the very top of the script, specify the shell you want to use:

#!/bin/bash
  1. 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

  1. 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

Script 1

Outcome:

Script 2

Outcome:

  1. 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