DEV Community

Kervie Sazon
Kervie Sazon

Posted on

Linux Fundamentals - Part 5: Bash Scripting (Hello World & Variables)

What Is Bash?

Bash stands for Bourne Again SHell.
It is the default shell on most Linux systems.
It allows you to:

  • Run commands interactively
  • Write scripts (files containing commands) A bash script is simply a text file with Linux commands executed line by line.

First Bash Script

Step 1: Create a file.
vim kervie.sh
This opens vim in Normal mode.

Step 2: Go to insert mode by pressing i.

Step 3: Add this content

#!/bin/bash
echo "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

Step 4: Save and exit
Press Esc then type :wq. to save the file.

Understanding the Script

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

It is called the shebang.
It tells Linux to use Bash to execute the script.

echo "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Prints text to the terminal.

Making the Script Executable

By default, scripts are not executable. Fix that with:
chmod +x kervie.sh

Running the Script

Run the script like this:
Type ./kervie.sh
Output:

Hello World!
Enter fullscreen mode Exit fullscreen mode

Introducing Variables in Bash

A variable allows you to store data and reuse it throughout your script.
Basic variable syntax:
variable_name=value
Important rules:
No spaces around '='.
Variable names are case-sensitive.

Script with Variables

Let’s create another script.
Step 1: Open a new file with Vim.

vim kvariable.sh
Enter fullscreen mode Exit fullscreen mode

Press i to enter Insert mode.

Step 2: Write the script

#!/bin/bash

name="Kervie Jay Sazon"
echo "Hello, $name!"
Enter fullscreen mode Exit fullscreen mode

Step 3: Save and exit
Press ESC, then:
:wq

Step 4: Make it executable and run it

chmod +x kvariable.sh

./kvariable.sh
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Kervie Jay Sazon!
Enter fullscreen mode Exit fullscreen mode

How Variables Work?

name="Kervie Jay Sazon"
Enter fullscreen mode Exit fullscreen mode

Stores text in a variable called name.

$name
Enter fullscreen mode Exit fullscreen mode

Retrieves the value stored in name.

Variables make scripts dynamic, reusable, and easier to maintain.

Note:
Do not add spaces around =.

name="Kervie jay"
Enter fullscreen mode Exit fullscreen mode

Don't forget $ when using variables.
Don't forget to make the script executable.
Example:

chmod +x kvariable.sh
Enter fullscreen mode Exit fullscreen mode

Running without ./.

Today, I have learned the basics of Bash scripting by creating my first script with Vim, printing output to the terminal, and understanding how variables work in Bash.

Tomorrow, I’ll continue my Bash scripting journey by learning basic math operations and if statements to introduce logic and decision-making into my scripts.

Top comments (0)