🖥️ Creating and Running Your First Bash Script

Pranav SavaniPranav Savani
2 min read

If you’ve been exploring Linux and repeating the same commands over and over, here’s a pro tip: you don’t have to. That’s what Bash scripts are for.

In this post, I’ll walk you through creating and running your first Bash script — using simple, real-world examples. If you’ve ever used echo, ls, or uptimeYou're more ready for this than you think.


What’s a Bash Script?

A Bash script is just a text file that contains a list of Linux commands.

Instead of typing commands manually every time, you can put them in a script and run them all at once, like clicking a “Run” button for your terminal.

You can use Bash scripts to:

  • Automate backups

  • Clean up old log files

  • Run multiple tasks at once

  • Save time and reduce mistakes


Step 1: Create a New Script File

Let’s start small.

Open your terminal and create a file:

bash

touch hello.sh

Then open it in your favorite editor:

bash

nano hello.sh

Or use VS Code, Vim — whatever you prefer.


Step 2: Add the Shebang

At the very top of the file, add this line:

bash

#!/bin/bash

This is called the shebang. It tells your system that this file should be run using the Bash shell.

Think of it like declaring the language for your script.


Step 3: Write Some Commands

Now, let’s add some basic commands:

bash

#!/bin/bash

echo "Hello, world!"
date
uptime

What this does:

  • Prints a friendly message

  • Shows the current date and time

  • Tells you how long your system has been running

Save the file. (If you’re using nano, it’s Ctrl + O → Enter → Ctrl + X.)


Step 4: Make It Executable

Before you can run the script, you need to permit it:

bash

chmod +x hello.sh

This makes it runnable like a program.


Step 5: Run Your Script

Now execute it:

bash

./hello.sh

You should see something like this:

yaml

Hello, world!
Mon Jul 1 10:17:12 IST 2025
 10:17:12 up 2 days,  5:12,  2 users,  load average: 0.18, 0.24, 0.17

That’s it. You’ve just written and run your first Bash script!


Bonus: A Real-World Example

Let’s say you want to automatically clean up log files older than 7 days from a directory.

Here’s a script for that:

bash

#!/bin/bash

LOG_DIR="/var/log/myapp"

echo "Cleaning up old log files in $LOG_DIR..."
find $LOG_DIR -type f -name "*.log" -mtime +7 -exec rm {} \;

echo "Done!"

You could schedule this script using cron to run every night, and never worry about overflowing logs again.

0
Subscribe to my newsletter

Read articles from Pranav Savani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pranav Savani
Pranav Savani