How to Write Your First Bash Script: Beginner’s Guide with Examples

A Bash script is a plain text file containing a series of commands that automate repetitive tasks on Linux, macOS, or Windows (via WSL). To write your first script, create a file ending in `.sh`, add `#!/bin/bash` at the top, write your commands, save it, then make it executable with `chmod +x script.sh` and run it with `./script.sh`. For example, a simple “Hello, World!” script looks like this:

“`bash

#!/bin/bash

echo “Hello, World!”

“`

Save it as `hello.sh`, run `chmod +x hello.sh`, then execute `./hello.sh`—you’ll see the output instantly. This guide walks you through every step with real examples, from basic syntax to practical automation scripts you can use today.

Bash script hello world terminal output example

Photo by Myburgh Roux on Pexels

## Why Use Bash Scripting?

Bash scripting saves time by automating repetitive tasks like file backups, system monitoring, or deployment steps. Instead of typing commands manually each time, you write a script once and reuse it. Key benefits:

  • Speed: Execute multiple commands in seconds.
  • Consistency: Eliminate human error in routine operations.
  • Flexibility: Combine with tools like `grep`, `awk`, or `cron` for powerful workflows.
  • Portability: Works on any Unix-like system without extra software.

## Setting Up Your Environment

Before writing scripts, ensure you have a terminal and a text editor. Most systems come with Bash pre-installed.

### Check Bash Availability

Open your terminal and type:

“`bash

bash –version

“`

If you see version info, you’re ready. On Windows, install Git Bash or enable WSL (Windows Subsystem for Linux).

### Choose a Text Editor

Use any plain text editor—avoid word processors like Word. Popular options:

  • Nano (terminal-based, beginner-friendly)
  • Vim (powerful but has a learning curve)
  • VS Code (graphical, with syntax highlighting)

## Your First Bash Script: Step-by-Step

### Step 1: Create the Script File

Open your terminal and navigate to your preferred directory:

“`bash

cd ~/scripts

mkdir -p ~/scripts

“`

Create a new file:

“`bash

touch myfirstscript.sh

“`

### Step 2: Add the Shebang Line

Edit the file and add `#!/bin/bash` as the first line. This tells the system to use the Bash interpreter.

### Step 3: Write Your Commands

Add commands line by line. For example, a script that prints system info:

“`bash

#!/bin/bash

echo “System Information”

echo “==================”

echo “Hostname: $(hostname)”

echo “Current user: $(whoami)”

echo “Date: $(date)”

“`

### Step 4: Save and Exit

In Nano: `Ctrl+O` to save, `Ctrl+X` to exit. In Vim: `:wq` and Enter.

### Step 5: Make It Executable

Run:

“`bash

chmod +x myfirstscript.sh

“`

### Step 6: Execute the Script

Run it with:

“`bash

./myfirstscript.sh

“`

You’ll see output like:

“`

System Information

==================

Hostname: my-pc

Current user: john

Date: Mon Mar 18 10:30:00 UTC 2025

“`

Bash script executing system info commands in terminal

Photo by Rafael Minguet Delgado on Pexels

## Essential Bash Scripting Concepts

### Variables

Store and reuse values:

“`bash

#!/bin/bash

name=”Alice”

echo “Hello, $name!”

“`

Use curly braces for clarity: `echo “Hello, ${name}!”`. Variables are case-sensitive and avoid spaces around `=`.

### User Input

Prompt users for input with `read`:

“`bash

#!/bin/bash

echo “Enter your name:”

read username

echo “Welcome, $username!”

“`

### Conditional Statements

Make decisions with `if`:

“`bash

#!/bin/bash

echo “Enter a number:”

read number

if [ $number -gt 10 ]; then

echo “Number is greater than 10”

else

echo “Number is 10 or less”

fi

“`

Common comparison operators:

Operator Meaning
`-eq` Equal to
`-ne` Not equal to
`-gt` Greater than
`-lt` Less than
`-f` File exists
`-d` Directory exists

### Loops

Repeat actions with `for` or `while`:

“`bash

#!/bin/bash

# For loop: print numbers 1 to 5

for i in 1 2 3 4 5; do

echo “Number: $i”

done

# While loop: countdown

count=5

while [ $count -gt 0 ]; do

echo “Countdown: $count”

((count–))

done

“`

### Functions

Group commands into reusable blocks:

“`bash

#!/bin/bash

greet() {

echo “Hello, $1!”

}

greet “Bob”

greet “Jane”

“`

## Practical Examples for Automation

### Example 1: Backup Script

Create a script to back up a directory to a timestamped archive:

“`bash

#!/bin/bash

backup_dir=”/home/user/documents”

dest=”/home/user/backups”

timestamp=$(date +%Y%m%d_%H%M%S)

filename=”backup_$timestamp.tar.gz”

tar -czf “$dest/$filename” “$backup_dir”

echo “Backup created: $dest/$filename”

“`

Save as `backup.sh`, make executable, and run it. Modify `backup_dir` and `dest` for your needs.

### Example 2: Log File Cleaner

Automatically delete logs older than 7 days:

“`bash

#!/bin/bash

log_dir=”/var/log/myapp”

days=7

find “$log_dir” -name “*.log” -mtime +$days -exec rm {} \;

echo “Deleted logs older than $days days from $log_dir”

“`

Test with `echo` instead of `rm` first to avoid accidents.

Bash script automating file backup and log cleanup tasks

Photo by serdar barış on Pexels

### Example 3: System Health Check

Monitor CPU, memory, and disk usage:

“`bash

#!/bin/bash

echo “=== System Health Report ===”

echo “Uptime: $(uptime -p)”

echo “Memory:”

free -h | grep Mem

echo “Disk Usage:”

df -h / | awk ‘NR==2 {print $5 ” used”}’

echo “CPU Load:”

top -bn1 | grep “Cpu(s)” | awk ‘{print $2 “%”}’

“`

Run this via cron for daily reports.

## Debugging Your Bash Scripts

Errors are common—use these techniques to fix them:

  • Add `-x` for execution trace: Run `bash -x script.sh` to see each command before it runs.
  • Check syntax with `bash -n`: `bash -n script.sh` reports syntax errors without executing.
  • Echo variable values: Insert `echo “DEBUG: variable=$variable”` to inspect state.
  • Use `set -e`: Stop script on first error by adding `set -e` at the top.

## Common Mistakes Beginners Make

Avoid these pitfalls:

  • Missing the shebang line: Scripts may run with wrong interpreter.
  • Spaces around `=` in variables: `name = “John”` fails—use `name=”John”`.
  • Forgetting to make executable: Run `chmod +x` every time.
  • Hardcoding paths: Use variables for flexibility.
  • Ignoring exit codes: Check `$?` after commands to handle failures.

## Comparison: Script vs. Manual Commands

Aspect Manual Commands Bash Script
Speed Slow, one by one Fast, batch execution
Repeatability Type each time Run anytime
Error-prone High Low (once tested)
Complexity Simple tasks Handles logic, loops
Sharing Not possible Share as `.sh` file

## Next Steps: Level Up Your Scripting

Once you’re comfortable, explore:

  • Command-line arguments: Use `$1`, `$2`, etc., to pass inputs.
  • Error handling: Trap signals and exit codes.
  • Scheduling: Add scripts to `cron` for automation.
  • Advanced tools: Integrate `sed`, `awk`, or `jq` for text processing.

Download ready-to-use automation scripts and DevOps tools from freefile.store to jumpstart your projects.

## Conclusion

You’ve just written your first Bash script and learned essential concepts like variables, conditionals, loops, and functions. Start with simple examples, test them thoroughly, and gradually build more complex automations. Bash scripting is a superpower for developers, sysadmins, and DevOps engineers—it turns hours of manual work into seconds of execution.

Ready to automate like a pro? Visit freefile.store to download free Bash scripts, automation templates, and DevOps tools that save you time. From backup utilities to deployment helpers, our library has everything you need to streamline your workflow. Start scripting today!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *