GICT knowledge base
How to Write a Basic Shell Script in Linux
Published
If you’ve ever typed the same few Linux commands over and over, you’ve probably wondered: “Isn’t there a way to automate this?” There is—and that’s where shell scripting comes in. Writing your own shell script is one of the simplest ways to make your computer do more work for you, and there’s no need to be a programming expert to get started.
Let’s break down the process, step by step, so you can go from copying-and-pasting commands to building your own custom scripts that save you time, reduce mistakes, and make you feel like a true Linux power user.
What Is a Shell Script, Really?
At its core, a shell script is just a plain text file containing a list of commands you’d normally type into your terminal. The “shell” is the program that interprets those commands (on most systems, it’s Bash). When you run the script, the shell reads and executes each line, one after the other.
Why is this so useful? Because anything you can do in the terminal, you can do in a script—only faster, more consistently, and with a lot less typing.
Why Should You Bother Writing Shell Scripts?
Let’s face it: computers are great at repetitive work. Humans…not so much. If you find yourself repeating a task, or if you want to automate steps that you always forget, a shell script is your best friend.
Here are just a few things you might use shell scripts for:
- Backing up a directory every night
- Renaming or converting a bunch of files
- Cleaning up log files or temporary data
- Installing your favorite packages on a new machine
- Kicking off a series of commands with a single double-click
Basically, if you’ve done it twice in the terminal, it’s probably a good candidate for automation.
What You Need to Write Your First Script
You don’t need much:
- A Linux system (even a virtual machine or Raspberry Pi is fine)
- Access to a terminal
- A plain text editor (nano, vim, emacs, or even gedit or VS Code)
- Curiosity and a willingness to experiment
That’s it! No fancy IDE or programming background required.
Anatomy of a Basic Shell Script
The heart of any shell script is a list of commands, but there’s one special line at the top called the “shebang.” It looks like this:
#!/bin/bash
This tells your system, “Hey, use Bash to run this script.” (You can swap /bin/bash for another shell if you want, but Bash is a great starting point.)
After the shebang, it’s just commands:
#!/bin/bash
echo "Hello, world!"
Save these two lines in a file, and congrats—you’ve written your first shell script!
Step-by-Step: Writing Your First Shell Script
Let’s go through the process together.
Step 1: Create the Script File
Open your terminal. To create a script called hello.sh, type:
nano hello.sh
This opens the Nano editor (you can use vim, emacs, or gedit if you prefer).
Step 2: Add the Shebang and Commands
Type these lines:
#!/bin/bash
echo "Welcome to your first shell script!"
date
whoami
The first line tells Linux to use Bash. The next lines are just regular commands you might type yourself: print a message, show the date, and print the current user’s name.
Step 3: Save and Exit
In Nano: Press Ctrl+O (to write the file), press Enter (to confirm), then Ctrl+X (to exit).
Step 4: Make the Script Executable
Before you can run your new script, you need to give it permission. Back at the terminal, type:
chmod +x hello.sh
Step 5: Run Your Script
Now, execute your script with:
./hello.sh
You should see:
Welcome to your first shell script!
[Current date and time]
[Your username]
Not bad for your first try, right?
Understanding Variables and Arguments
One of the most useful features of shell scripts is that you can store information in variables and use it later.
Example:
#!/bin/bash
name="Alice"
echo "Hello, $name!"
If you want your script to greet anyone, not just Alice, you can let the user input their name:
#!/bin/bash
echo "What is your name?"
read name
echo "Nice to meet you, $name!"
Even better, you can pass arguments to your script:
#!/bin/bash
echo "Hello, $1!"
Now run:
./hello.sh Bob
And you’ll get:
Hello, Bob!
Here, $1 refers to the first argument. You can use $2, $3, etc., for more.
Adding Comments
Comments are lines that start with # and are ignored by the shell. Use them to explain what your script is doing:
# This script greets the user
echo "Hello, $USER!"
Trust me: three months from now, you’ll be glad you added explanations.
Using Conditionals: Making Decisions in Your Script
Sometimes, you want your script to do something only if a condition is true.
Here’s a simple example:
#!/bin/bash
echo "Enter a number:"
read num
if [ "$num" -gt 10 ]; then
echo "That's a big number!"
else
echo "That's a small number!"
fi
This script checks if the entered number is greater than 10 and prints a message.
Loops: Doing Something Multiple Times
Want to do something for each file in a folder? That’s what loops are for.
#!/bin/bash
for file in *.txt; do
echo "Processing $file"
# Maybe add more commands here
done
This loop goes through every .txt file in the current directory and echoes its name.
Real-World Basic Shell Script Examples
Let’s look at a few scripts you might actually use.
Example 1: Back Up a Directory
#!/bin/bash
src="/home/$USER/Documents"
dest="/home/$USER/backup"
mkdir -p "$dest"
cp -r "$src"/* "$dest"/
echo "Backup complete!"
Example 2: Check Disk Space and Warn If Low
#!/bin/bash
usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$usage" -ge 80 ]; then
echo "Warning: Your disk is $usage% full!"
else
echo "Disk space is fine."
fi
Example 3: Greet All Logged-In Users
#!/bin/bash
users=$(who | awk '{print $1}' | sort | uniq)
for user in $users; do
echo "Hi, $user!"
done
Running and Debugging Your Scripts
To run a script, you can always use:
./myscript.sh
If you see “Permission denied,” you probably forgot to use chmod +x myscript.sh.
If you get “command not found,” double-check your spelling and make sure you’re in the right directory.
Want to see what your script is actually doing, step by step? Add this line after the shebang:
set -x
It’ll print each command as it runs, which is super handy for debugging.
Common Mistakes and How to Fix Them
- Forgetting the Shebang Your script might run in a different shell, leading to weird errors. Always start with
#!/bin/bash. - Not Making the Script Executable Use
chmod +x myscript.shto avoid permission errors. - Spaces Around Equals in Variables This won’t work:
name = "Alice"This will:name="Alice" - Missing Quotes Using quotes around variables prevents problems with spaces and special characters.
- Scripts Not in Your PATH If you want to run your script from anywhere, move it to a directory in your PATH (like
~/bin) or add that directory to your PATH.
Best Practices for New Scripters
- Start small. Automate a task you do often.
- Use comments throughout for clarity.
- Test your script on non-critical data first.
- Google is your friend. There’s a solution for almost every scripting problem out there.
- Read man pages. For any command, try
man commandname. - Share and ask for feedback. Linux forums and communities are full of people who love helping newcomers learn scripting.
Frequently Asked Questions (FAQ)
Do I need to know programming to write a shell script?
Not at all! If you can use the terminal, you can start writing scripts.
What’s the difference between Bash, sh, and other shells?
Bash is the most common shell on Linux. sh is more basic and universal. Most beginner scripts use Bash syntax.
How do I schedule a script to run automatically?
Use crontab -e to schedule scripts. For example, run a backup every night.
Can I use GUI dialogs in shell scripts?
Yes, with tools like zenity or kdialog, but that’s more advanced.
Can shell scripts run on macOS?
Absolutely! Just make sure your syntax matches the shell version (macOS uses Bash or Zsh by default).
Conclusion
Learning to write basic shell scripts opens up a whole new world on Linux. You’ll save time, automate boring chores, and feel far more in control of your computer. Start with a simple “Hello, world!” and grow from there—soon you’ll be chaining commands, using variables, and maybe even sharing scripts with friends or coworkers.
Most importantly, don’t be afraid to experiment. The best scripts are written by people who weren’t scared to break something along the way.
Related guides
Writing Shell Completion for Your Own Scripts: Bash Tab Completion From Scratch
You have a script called serverctl that deploys, checks, and rolls back services on your VPS.
Linux ScriptingHow to Use the trap Command in Bash
Learn how to use the trap command in Bash to gracefully handle script interruptions, clean up resources, and improve your error handling practices.
