Skip to content

01. Bash Shell Script

What is a Bash Script?

A Bash script is a text file containing a series of commands that you would normally type in the terminal.
Instead of executing commands manually, a script automates them — saving time and reducing errors.


Step 1: Locate Your Bash Interpreter

Before writing a script, find out where Bash is installed on your system.

$ which bash
/bin/bash

This tells you that the Bash interpreter is located in /bin/bash.
You’ll need this path for the shebang line (explained next).


What is a Shebang?

Every Bash script starts with a special line called a shebang.

#!/bin/bash

Explanation:

  • #! — Marks the file as a script and tells the system which interpreter to use.

  • /bin/bash — The path to the Bash interpreter.

This line ensures the script runs in the correct shell, regardless of the user’s default shell.


Step 2: Create a Simple Script

Let’s create your first Bash script using nano editor.

$ nano hello_world.sh

Paste the following content:

#!/bin/bash
# 01. Bash Shell Script
STRING="Hello World"
# print variable on a screen
echo $STRING

Explanation:

  • STRING="Hello World" — Creates a variable named STRING.

  • echo $STRING — Prints the variable’s value to the terminal.

Save and exit the file (Ctrl + O, Enter, then Ctrl + X).


Step 3: Make the Script Executable

Before running a script, you must give it execute permission.

$ chmod +x hello_world.sh

Explanation:

  • chmod — Changes file permissions.

  • +x — Adds execute permission to the file.

  • Now the script can be run directly from the command line.


Step 4: Run the Script

Execute your script using:

$ ./hello_world.sh

Output:

Hello World

Congratulations! You’ve written and executed your first Bash script.


Example 2: Simple Backup Script

You can automate repetitive tasks, such as creating backups.

Script:

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/linuxconfig

Explanation:

  • tar — Archive utility used to combine and compress files.

  • -c — Create a new archive.

  • -z — Compress the archive using gzip.

  • -f — Specify the filename (myhome_directory.tar.gz).

  • /home/linuxconfig — The directory being backed up.

Result:

Running this script creates a compressed backup of /home/linuxconfig in the current directory.

$ ./backup.sh

Output:

myhome_directory.tar.gz created successfully

Why Use Bash Scripts?

Benefit Description
Automation Run repetitive tasks automatically.
Consistency Same commands executed every time — fewer errors.
Expandability Start simple, add logic later (loops, conditions, etc.).
Efficiency Save time and effort by not typing long commands repeatedly.

Summary

Step Command Purpose
1️ which bash Find Bash interpreter path
2️ nano hello_world.sh Create script file
3️ chmod +x hello_world.sh Make script executable
4️ ./hello_world.sh Run the script