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.
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.
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.
Paste the following content:
Explanation:¶
-
STRING="Hello World"— Creates a variable namedSTRING. -
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.
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:
Output:¶
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:¶
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.
Output:
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 |