DEV Community

Cover image for Learn Bash Scripting With Me ๐Ÿš€ - Day 2
Babs
Babs

Posted on

Learn Bash Scripting With Me ๐Ÿš€ - Day 2

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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 1

  • Script 1 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
Enter fullscreen mode Exit fullscreen mode
  • If itโ€™s not executable, make it executable with:
chmod +x variables.sh
Enter fullscreen mode Exit fullscreen mode
  • 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)