## π Author
Birat Aryal β birataryal.github.io
Created Date: 2025-06-23
Updated Date: Monday 23rd June 2025 07:56:46
Website - birataryal.com.np
Repository - Birat Aryal
LinkedIn - Birat Aryal
DevSecOps Engineer | System Engineer | Cyber Security Analyst | Network Engineer
π Bash Scripting for Beginners
This guide is a starting point for learning Bash scripting on Linux. It covers basic syntax, variables, conditionals, loops, and useful examples to get you going.
π What is Bash?
Bash (Bourne Again SHell) is a Unix shell and command language. Bash scripts allow you to automate tasks, chain commands, and create custom tools.
π Getting Started
πΉ Create a Bash Script
-
Open a terminal.
-
Create a file:
touch hello.sh
- Make it executable:
chmod +x hello.sh
- Add a shebang at the top of the file:
#!/bin/bash
/bin/bash denotes the shell which would be used.
π€ Basic Script Example
#!/bin/bash
echo "Hello, World!"
Run it:
./hello.sh
π§ Variables
#!/bin/bash
name="Birat"
echo "Hello, $name!"
π₯ Read User Input
#!/bin/bash
echo "What's your name? "
read name
echo "Welcome, $name!"
Tip
You could use on single line to get input from user like this:
#!/bin/bash
read -p "What's your name? " name
echo "Welcome, $name!"
π Conditionals
#!/bin/bash
echo "Enter a number:"
read num
if [ "$num" -gt 10 ]; then
echo "Number is greater than 10"
else
echo "Number is 10 or less"
fi
Syntax
if [ condition ]; then
# if-block
else
# else-block
fi
π Loops
For Loop
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
Syntax
for variable in list
do
commands
done
While Loop
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count is $count"
count=$((count + 1))
done
Syntax
while [ condition ]
do
commands
done
π File Check Example
#!/bin/bash
file="/etc/passwd"
if [ -f "$file" ]; then
echo "$file exists."
else
echo "$file does not exist."
fi
π Directory Listing with Loop
#!/bin/bash
for file in *.txt; do
echo "Found text file: $file"
done
π§ Functions
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Birat"
π Command Line Arguments
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
Run with:
./script.sh one two
π¦ Exit Status
#!/bin/bash
ls /etc/passwd
echo "Exit status: $?"
π Sample Real Script: Backup Files
#!/bin/bash
src_dir="/home/user/docs"
backup_dir="/home/user/backup"
mkdir -p "$backup_dir"
cp -r "$src_dir"/* "$backup_dir"
echo "Backup complete!"
Tips
-
Use
chmod +x script.shto make your script executable. -
Use
set -xto debug your script. -
Always double quotes variables:
"$var" -
Single quotes does not return the value defined for variables:
'$var' -
Test with
bash -n script.shfor syntax checking.
π§ͺ Practice Challenge
Try writing a script that:
-
Asks for a username.
-
Checks if the user exists on the system.
-
If yes, prints their home directory.
-
Else, prints a message.
π§ͺBasic BashScripting FlowChart
Tip
Based on the diagram below everything could be configured using the bash scripting.
