Codelivly

linux bash shell

So, you’ve heard about Bash scripting and you’re curious what all the buzz is about? Whether you’re just starting with Linux or diving deeper into automation, Bash scripts are your best friend. They’re like small sets of instructions that you write once, and they do the boring stuff for you—over and over again. Want to automate tasks, backup files, or monitor your system? Bash can do all that—and more.

In simple terms, a bash script is just a text file full of Linux commands, strung together with a bit of logic so the system knows what to do, when to do it, and how to react. It’s like giving your terminal a to-do list. Once you understand how to write one, it unlocks a whole new world of productivity.

This guide is all about helping you learn how to create a bash script, even if you’ve never written one before. We’ll walk through everything—from the basics like how to save a .sh file, to cool stuff like adding logic, loops, and even automated tasks using cron.

If you’ve ever typed commands in the terminal and thought, “I wish I didn’t have to do this manually every time,” you’re in the right place. This is bash scripting for beginners, explained step-by-step in plain English. By the end, you’ll not only know how to create bash scripts—but also how to use them to make your Linux experience 10x more powerful.

Let’s dive in and start writing your first Linux bash script!

Understanding the Linux Shell

If you’ve ever used Linux, chances are you’ve come across the terminal — that black screen with blinking text where things look both mysterious and powerful. Well, that’s where Bash scripting comes into play. A Bash script is like a cheat code that tells your Linux system what to do, step by step, automatically.

In plain terms: a Bash script is a series of commands written in a file, which the Linux shell can execute one after another. Instead of typing commands manually every time, you write them once and let the script do the job for you.

So, why learn Bash scripting?
Because it saves you time, reduces errors, and makes you feel like a Linux wizard 🔮. Whether you’re a developer, system admin, ethical hacker, or just a curious beginner, learning how to write Bash scripts in Linux will make your workflow smoother and smarter.

You can use Bash scripts to:

  • Automate repetitive tasks
  • Manage files and backups
  • Monitor system health
  • Schedule cron jobs
  • Even build tools for hacking, devops, or daily routines

This guide is here to teach you how to create a Linux Bash script from scratch, and show you what cool things you can do with it. Don’t worry — you don’t need to be a coding expert. Just a terminal, a bit of curiosity, and this article.

Before we dive into scripting, let’s understand what the Linux shell actually is.

Think of the shell as a translator between you and the computer. When you type commands into the terminal, the shell interprets them and gets your Linux system to respond.

There are different types of shells in Linux, but the most popular one (and the one we’re focusing on here) is Bash, which stands for Bourne Again SHell.

Shell vs Terminal vs Bash — What’s the Difference?

  • Terminal: This is the window or app you use to interact with the system.
  • Shell: This is the program that runs inside the terminal, interpreting your commands.
  • Bash: This is one type of shell — and the most widely used on Linux systems.

In short:

You type commands in the terminal ➜ The shell (Bash) reads them ➜ The computer executes them.

🥊 Bash vs Other Shells

There are other shells like:

  • Zsh (popular for customization)
  • Fish (user-friendly and interactive)
  • Dash (lightweight, faster in some systems)

But Bash is still the king when it comes to scripting, especially on most Linux distros.

Why Learn Bash?

  • It’s pre-installed on almost every Linux system
  • Used in DevOps, SysAdmin, Security, and Automation
  • Works great for small to mid-sized automation tasks
  • A solid stepping stone for learning more advanced scripting languages later

Discover: Bash scripting tips that can save time on Linux

Getting Started with Bash Scripting

Alright, let’s roll up our sleeves and create our very first Bash script. If you’ve never written a line of code before — don’t worry. Bash scripting is surprisingly beginner-friendly. This section will walk you through everything step by step.

What You Need to Start

To begin writing Bash scripts, you only need two things:

  • A Linux system (or WSL on Windows, or a Linux VM like Ubuntu)
  • A text editor (like nano, vim, or even Visual Studio Code)

That’s it. No setup wizard, no installations. Everything you need is already in your system.

✍️ Step 1: Create a New Script File

Open your terminal and run this:

nano myscript.sh

This opens a new file called myscript.sh in the nano editor (which is beginner-friendly and comes pre-installed).

🔧 Step 2: Add the Shebang Line

The first line in every Bash script should tell Linux which interpreter to use. That’s where the shebang comes in:

#!/bin/bash

This line means: “Hey Linux, use the Bash shell to run this file.”

📝 Step 3: Write Your First Commands

Below the shebang, type a couple of commands:

#!/bin/bash
echo "Hello, world!"
echo "This is my first Bash script."

This is your first working Bash script. 🎉

🔒 Step 4: Make It Executable

By default, new files aren’t allowed to run. To fix that, make it executable:

chmod +x myscript.sh

This command gives the script permission to run like a program.


▶️ Step 5: Run the Script

Now run it like this:

./myscript.sh

You should see:

Hello, world!
This is my first Bash script.

Congrats — you’ve just written and executed your first Bash script!

Pro Tip: Naming Conventions

Keep your scripts lowercase, and use underscores to separate words (e.g., backup_files.sh). It’s a good habit and improves readability.

Why This Is So Powerful

Imagine writing dozens of terminal commands every day. What if you could just run one script to do it all?

That’s the beauty of Bash scripting:
It turns your command-line experience into a powerful automation tool.

Bash Script Fundamentals

Now that you’ve written your first Bash script, let’s dive into the building blocks of any good script. This section is all about understanding the core fundamentals that make your script functional, powerful, and flexible.

Think of this as your Bash scripting toolkit — things like variables, user input, printing messages, and using built-in commands. These basics will form the foundation for everything you automate later.

📚 Want to go deeper and build real-world tools?
Check out our best-selling eBook:
👉 Master Shell Scripting: Build Custom Tools & Automate Pentesting
It’s packed with hands-on projects, practical use cases, and tips for automating your ethical hacking workflows like a pro.

Variables in Bash

A variable is like a box where you store some data. Here’s how you declare one:

name="Sunil"
echo "Hello, $name"

Notice there’s no space around the = sign — that’s important!
Use $variable_name to get the value.

Quick tip:

age=25
echo "You are $age years old"

You can store anything — numbers, strings, file names, commands, etc.

Using echo to Print Output

The echo command is used to print messages to the screen.

echo "Welcome to Bash scripting!"

You can also use it to print variables:

user="Alice"
echo "Logged in as $user"

Taking User Input with read

Want your script to interact with the user? Use read:

echo "Enter your name:"
read username
echo "Hello, $username!"

This makes your script dynamic and user-friendly.

Some Handy Built-in Commands

CommandWhat It Does
pwdPrints the current directory
lsLists files in the directory
clearClears the terminal screen
dateShows current date & time
whoamiDisplays your username

Try combining them in your script to create a welcome dashboard!

Summary

By mastering variables, echo, and read, you’ve just unlocked a whole new level of scripting control. These basics may look small, but they’re used in almost every Bash script — whether it’s for DevOps automation, file management, or even custom pentesting tools.

Ready to go pro? 🚀
Grab your copy of our book:
👉 Master Shell Scripting and start automating like a hacker 💻

Controlling Script Flow

Now that you know how to use variables and print stuff, it’s time to give your script some brains 🧠. This is where control flow comes in — using conditions, decisions, and loops to make your Bash script behave intelligently.

This section teaches you how to use:

  • if, else, elif for decision-making
  • case statements for menu-style logic
  • for, while, and until loops for automation

Once you master these, you can build interactive scripts, automations, system checkers, and much more.

If, Else, and Elif

Let’s start with conditional statements — useful when your script needs to make a decision.

#!/bin/bash

echo "Enter your age:"
read age

if [ $age -ge 18 ]; then
  echo "You're an adult."
elif [ $age -ge 13 ]; then
  echo "You're a teenager."
else
  echo "You're a kid."
fi

🔍 -ge means “greater than or equal to”. Bash uses [ ] for conditions.

Case Statements

The case command is like a smart switch — perfect when you have multiple options.

#!/bin/bash

echo "Choose a fruit: apple, banana, mango"
read fruit

case $fruit in
  apple)
    echo "You chose apple";;
  banana)
    echo "Banana is rich in potassium!";;
  mango)
    echo "Mango is the king of fruits!";;
  *)
    echo "Unknown fruit";;
esac

This is great for CLI menus and automation tools.

For Loops

Loops are used to repeat actions — a key ingredient in automation.

for i in 1 2 3 4 5
do
  echo "Loop number: $i"
done

Or loop through files:

for file in *.txt
do
  echo "Found file: $file"
done

While Loops

The while loop keeps running as long as a condition is true:

count=1
while [ $count -le 5 ]
do
  echo "Count is: $count"
  ((count++))
done

You can also use it to create waiting scripts or menu systems.

Until Loops

An until loop runs until a condition becomes true (opposite of while):

number=0
until [ $number -eq 5 ]
do
  echo "Number: $number"
  ((number++))
done

Combine Flow with Power

Once you master these, you can do things like:

  • Run auto-update scripts
  • Build interactive bash tools
  • Write pentesting automations
  • And create error-handling logic

If you want real-world use cases (and pentesting tools), grab our in-depth guide:
👉 Master Shell Scripting: Build Custom Tools & Automate Pentesting — it’s got complete walkthroughs and projects for serious scripting.

Handling Arguments and Parameters

Let’s say you want your Bash script to accept input directly from the command line — like when you run python app.py hello. That’s where arguments and parameters come in.

Instead of hardcoding data, you can pass it in when you run the script. This makes your script flexible, powerful, and useful for automation tools, penetration testing, or DevOps workflows.

Accessing Command Line Arguments

In Bash, command line inputs are stored in special variables:

  • $0 — Name of the script
  • $1, $2, $3 — First, second, third arguments
  • $@ — All arguments as separate words
  • $# — Total number of arguments

Example script:

#!/bin/bash

echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "All Arguments: $@"
echo "Total Arguments: $#"

Run it like this:

./myscript.sh hello world

Output:

Script Name: ./myscript.sh
First Argument: hello
Second Argument: world
All Arguments: hello world
Total Arguments: 2

This is great for CLI tools, automation scripts, and pentest utilities.

Example: A Simple Calculator

Let’s say you want to pass two numbers and get their sum:

#!/bin/bash

num1=$1
num2=$2

sum=$((num1 + num2))
echo "Sum is: $sum"

Usage:

./calc.sh 10 15

Using getopts for Flags (Optional, But Powerful)

Want named parameters like -u for username? Use getopts.

#!/bin/bash

while getopts u:p: flag
do
  case "${flag}" in
    u) username=${OPTARG};;
    p) password=${OPTARG};;
  esac
done

echo "Username: $username"
echo "Password: $password"

Run it like:

./login.sh -u sunil -p 1234

This is how many Linux command-line tools work behind the scenes.

Pro Tip: Validate Inputs

Always check if the user actually passed something:

if [ -z "$1" ]; then
  echo "Usage: $0 <your-name>"
  exit 1
fi

Take Your Scripts to the Next Level

Now that you’re accepting user input directly from the terminal, your Bash scripts are no longer static — they’re dynamic, reusable, and adaptable.

Want to learn how to build full custom CLI tools, hacking utilities, or server scripts using this?
👉 Grab our guide: Master Shell Scripting – perfect for leveling up your automation and pentesting game.

Working with Files and Directories

One of the most powerful (and practical) things you can do with Bash scripting is automate file and folder operations. Think about it — Linux is built around files. If you can script file creation, movement, backup, and cleanup, you can automate everything from log management to system reports to file-based attacks in security audits.

This section walks you through essential file-handling commands and how to use them in your Bash scripts.

Creating and Writing Files

Want to create a new file inside your script? Easy:

touch report.txt
echo "Report generated on $(date)" > report.txt

Use > to write (overwrite) and >> to append:

echo "New entry" >> report.txt

You can also use cat to dump data into a file:

cat > notes.txt << EOF
This is a multi-line
Bash-generated file.
EOF

Creating Directories

mkdir backups

Want to make a folder only if it doesn’t already exist?

[ ! -d "backups" ] && mkdir backups

Moving, Copying, and Deleting

Move a file:

mv file.txt /home/user/Documents/

Copy it:

cp config.sh config_backup.sh

Delete it:

rm old_file.log

You can even bulk delete with wildcards:

rm *.tmp

⚠️ Be careful with rm — always double-check before running!

Example: Simple Backup Script

#!/bin/bash

src_folder="/home/user/Documents"
backup_folder="/home/user/Backups"

mkdir -p $backup_folder
cp -r $src_folder/* $backup_folder/

echo "Backup completed at $(date)" >> $backup_folder/backup.log

Automate it with cron and you’ve got a daily backup system — hands-free.

File Checks You Should Know

[ -f file.txt ]     # Is it a file?
[ -d foldername ]   # Is it a directory?
[ -r file.txt ]     # Is it readable?
[ -w file.txt ]     # Is it writable?
[ -e file.txt ]     # Does it exist?

These conditions are great for safe scripting, especially in automated pentesting, log monitoring, or user data scripts.

Automate More with Bash

With just these commands, you can:

  • Archive logs
  • Rename files in bulk
  • Sort and clean directories
  • Build intelligent file watchers
  • Set up auto-backup solutions
  • Even build data exfiltration tools (for legal pentesting!)

🔐 Want hands-on projects like this?
✅ Download our step-by-step guide:
👉 Master Shell Scripting: Build Custom Tools & Automate Pentesting
You’ll learn how to turn basic file scripts into powerful tools used by sysadmins and ethical hackers alike.

Discover: How I use Bash to automate tasks on Linux

Practical Bash Scripting Examples

Now that you know the core of Bash scripting — variables, flow control, file handling — let’s put it all into action. This is where Bash becomes fun, and honestly, pretty addictive.

You’ll learn how to automate everyday tasks like backups, file renaming, disk space checks, and even schedule jobs. These are the kinds of scripts that make sysadmins, developers, and ethical hackers more efficient and powerful.

1. Automated Backup Script

#!/bin/bash

src="/home/user/Documents"
dest="/home/user/Backups/$(date +%F_%T)"

mkdir -p "$dest"
cp -r "$src"/* "$dest"

echo "Backup done at $(date)" >> "$dest/backup.log"

This script:

  • Creates a timestamped folder
  • Copies your files
  • Logs the backup time

Perfect for daily backups or cron jobs.

2. Bulk File Renamer

#!/bin/bash

count=1
for file in *.jpg
do
  mv "$file" "image_$count.jpg"
  ((count++))
done

This renames all .jpg files in a folder to image_1.jpg, image_2.jpg, etc.
Great for organizing photo dumps, downloads, or scraped content.

3. Disk Space Monitor

#!/bin/bash

threshold=80
usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')

if [ "$usage" -gt "$threshold" ]; then
  echo "⚠️ Disk space is above $threshold%! Used: $usage%" | mail -s "Disk Alert" [email protected]
fi

This script checks if disk usage goes above a limit, and sends an alert.
Sysadmins love this one.

4. Port Scanner (Ethical Pentesting)

#!/bin/bash

host=$1

for port in {1..100}
do
  timeout 1 bash -c "echo > /dev/tcp/$host/$port" 2>/dev/null &&
  echo "Port $port is open"
done

Usage:

./scanner.sh 192.168.1.1

This scans ports 1–100 on a given host — great for security testing and learning how tools like Nmap work.

5. Scheduled Reminder

#!/bin/bash

echo "Drink Water Reminder - $(date)" >> reminders.txt

Add it to crontab:

*/60 * * * * /path/to/reminder.sh

It logs a hydration reminder every hour. Or replace it with anything you want to be reminded of.

6. Auto Update and Reboot Script

#!/bin/bash

sudo apt update && sudo apt upgrade -y
echo "System updated at $(date)" >> /var/log/update.log
sudo reboot

Run this weekly with cron and never worry about updates again.

Build Tools Like These (and More)

This is just the tip of the iceberg. With a bit of creativity, you can:

  • Build your own CLI apps
  • Automate reporting and scanning
  • Replace GUI tools with command-line ones
  • Make reusable scripts for dev, cloud, or cybersecurity tasks

🎯 Want to master real-life Bash scripting with practical, hands-on projects?
👉 Grab the guide: Master Shell Scripting: Build Custom Tools & Automate Pentesting
Perfect for beginners who want to go from “Hello World” to building pro-level tools.

🧭Next Steps and Resources

So, you’ve written your first Bash script, automated tasks, created condition-based logic, and even handled files like a Linux pro. Nice work!

But Bash scripting isn’t a one-and-done skill — it’s something you can keep getting better at, especially if you’re heading into DevOps, ethical hacking, cloud infrastructure, or just want to become a Linux power user.

What You Should Do Next

  1. Practice Daily
    Try writing at least one small script each day — even something simple like automating your directory cleanup or checking internet speed.
  2. Contribute to Open Source or GitHub Projects
    Look for Bash-related issues or small projects you can help with. It’s a great way to learn from real code and grow faster.
  3. Use Bash in Real Projects
    Start integrating Bash into your personal tools, setup scripts, cron jobs, or pentesting environments.
  4. Explore Advanced Scripting Concepts
    Topics like trap, select, signal handling, functions, and debugging tools (set -x, shellcheck) are next-level skills that really polish your scripts.

Free & Paid Learning Resources

Here’s a handpicked list of resources to continue your journey:

  • Master Shell Scripting: Build Custom Tools & Automate Pentesting
    This guide goes beyond “Hello World” and helps you write Bash scripts for real-world problems, especially in cybersecurity and DevOps. If you liked this article, you’ll love the book.
  • 📘 The Linux Command Line by William Shotts
    A free classic book to master the shell, great for absolute beginners.
  • 🎓 Linux Journey (https://linuxjourney.com)
    A fun and interactive way to learn Linux concepts.
  • 🛠️ ShellCheck (https://www.shellcheck.net)
    An online linter to debug and clean up your scripts.
  • 📺 YouTube Channels like:
    • NetworkChuck
    • The Cyber Mentor
    • DorianDotSlash (Bash-focused content)

Discover: Mastering Bash: A Cheat Sheet of the Top 25 Commands and Creating Custom Commands

Keep Building, Keep Automating

Whether you’re a student, ethical hacker, aspiring DevOps engineer, or just love tinkering with Linux, Bash scripting gives you superpowers in the command line.

Every time you automate a task, solve a real problem, or speed up your workflow, you’re proving that scripting isn’t just about writing code — it’s about making life easier.

And when you’re ready to go further — building pentesting tools, cloud scripts, or full automation flows — we’ve got your back 👇

🧠 Grab the full guide:
👉 Master Shell Scripting — Build custom tools, automate real-world tasks, and become a shell pro.

Conclusion: You’re Now a Bash Scripter!

Congratulations — you’ve officially taken your first steps into the powerful world of Linux Bash scripting!

What started with a simple echo "Hello, world" has now grown into writing dynamic scripts, building automation tools, scanning networks, backing up files, and handling real-world workflows — all using the humble terminal.

Bash scripting might seem old-school at first glance, but it’s one of the most practical and in-demand skills for:

  • System Administrators
  • Cybersecurity Enthusiasts
  • DevOps Engineers
  • Hackers and Pentesters
  • Anyone who wants to automate boring stuff

You don’t need to memorize everything. The real secret? Practice. Experiment. Break things. Fix them. Repeat.

The terminal is your playground now. Own it.

Want to go even deeper?

If you’re passionate about turning your Bash skills into automated hacking tools, system exploits, and real-time recon workflows, then don’t miss:

  • 👉 Linux Playbook for Hackers
    Your no-BS guide to mastering Linux from a hacker’s perspective — packed with practical scripts, commands, and use cases.

And if you haven’t already:

  • 💻 Master Shell Scripting
    This is the ultimate guide to writing powerful Bash tools for automating everything from server tasks to pentests.

Whether you’re a beginner just learning how to create Bash scripts or an aspiring ethical hacker, remember:

🚀 “Automation is the difference between working hard and working smart.”

And now — you’re working smart.

Our Latest Update