How to Create a Linux Bash Script: A Practical Guide
In this article
Yes, you can create a Linux bash script with nothing more than a text editor and a terminal. A bash script is a plain text file containing a series of commands that the Bash shell executes in order. It lets you automate repetitive tasks, batch-process files, run backups, monitor system health, and even build simple menus. This guide walks you through creating your first script, adding permissions, and running it—plus common pitfalls and troubleshooting.
What You'll Need
- A Linux system (or Windows Subsystem for Linux) with the Bash shell installed—this is standard on virtually all distributions.
- A text editor:
nano(easiest for beginners),vim, or any GUI editor like gedit. - Terminal access (Ctrl+Alt+T on most desktops).
- Basic familiarity with Linux commands like
ls,cd, andchmod—but you can follow along even if you're new.
Step-by-Step
- Open a terminal and navigate to the directory where you want to create the script. For example:
cd ~/scripts(create that folder first if needed:mkdir ~/scripts). - Create a new file with a
.shextension, though the extension is not mandatory. Usenano myscript.shto open the nano editor. - Add the shebang line as the very first line:
#!/bin/bash. This tells the system which interpreter to use. Without it, the script may not run correctly. - Write your commands on separate lines. For a first script, try something simple:
#!/bin/bash echo "Hello, world!" date ls -la
Save with Ctrl+O, then Exit with Ctrl+X. - Make the script executable with:
chmod +x myscript.sh. This grants execute permission—without it, you'll get a "Permission denied" error. - Run the script from the current directory using:
./myscript.sh. The./is required to tell Bash to look in the current directory. - Add variables and logic to make it more useful. For example:
#!/bin/bash NAME="world" echo "Hello, $NAME!" if [ -d "/tmp" ]; then echo "/tmp exists" fi
Save, make executable again if needed, and run it. - Use command substitution to capture output. Example:
current_dir=$(pwd)thenecho "You are in $current_dir". - Accept user input with
read:read -p "Enter your name: " user_namethenecho "Hi $user_name". - Add loops for repetitive tasks. A simple
forloop:for file in *.txt; do echo "Processing $file"
Add commands here
done - Test with a real task—for instance, a backup script that copies files to a folder with a timestamp:
#!/bin/bash backup_dir=~/backups/$(date +%Y%m%d) mkdir -p "$backup_dir" cp ~/Documents/*.txt "$backup_dir" echo "Backup done to $backup_dir"
- Schedule it with cron (optional) to run automatically. Use
crontab -eand add a line like0 2 * * * /home/you/scripts/backup.shto run daily at 2 AM. Ensure the script is executable and has a shebang.
Common Mistakes
- Forgetting the shebang—the script may run but with unexpected behavior, especially if you use Bash-specific features.
- Not making the script executable—you'll see "Permission denied" when trying to run it.
- Using spaces around the equals sign in variable assignments—
name = "John"is wrong; it must bename="John". - Missing quotes around variables—especially when paths contain spaces. Always use
"$var"unless you intentionally want word splitting. - Running the script with
shinstead ofbash—shmay point to dash on some systems, which lacks Bash features. Use./script.shorbash script.sh. - Using Windows line endings—if you edit on Windows, the
\rcharacters can cause errors. Convert withdos2unix script.sh.
Tips
- Start simple—write one command at a time and test before adding complexity.
- Use
set -eat the top to make the script exit on any error, which helps catch problems early. - Add comments with
#to explain what each section does—future you will thank you. - Use
echostatements to print progress messages, especially during long operations. - Test with sample files in a temporary directory before running on real data.
- Keep scripts in a dedicated folder like
~/scriptsand add that folder to yourPATHif you want to run them from anywhere. - Check for existing tools—many tasks already have commands like
rsyncfor backups orffmpegfor media; your script can simply call them.
Troubleshooting
- Script won't run: "Permission denied"—Run
chmod +x script.shto add execute permission. - Script runs but does nothing—Check for typos in commands, and run
bash -x script.shto trace each line as it executes. - "Command not found" errors—Make sure the command is installed (e.g.,
which rsync) and that your script's PATH includes the right directories. For custom commands, use the full path or add to PATH. - Variables not expanding—Ensure you used
$VARor${VAR}, notVARalone, and that the variable is defined before use. - Unexpected line endings—If you see
\rin error messages, runsed -i 's/\r$//' script.shordos2unix. - Script works manually but fails in cron—Cron runs with a minimal environment. Use absolute paths (e.g.,
/home/you/scripts/backup.sh) and set variables likeHOMEat the top of the script if needed. - If nothing helps—Search the exact error message online (e.g., on Stack Exchange) or ask a colleague; most issues are common and well-documented.
Frequently Asked Questions
Do I need to install anything to write bash scripts?
No—Bash is included by default on virtually all Linux distributions. You only need a text editor and terminal.
Can I run a bash script on Windows?
Yes, using Windows Subsystem for Linux (WSL) or Git Bash. WSL provides a full Linux environment, while Git Bash offers a Bash-like shell with many common commands.
What's the difference between bash script.sh and ./script.sh?
The first explicitly invokes Bash to interpret the file. The second uses the shebang line to determine the interpreter and requires execute permission. Both work, but ./script.sh is more standard.
How do I pass arguments to a script?
Inside the script, $1, $2, etc., refer to the first, second, etc., arguments. For example, if you run ./script.sh foo bar, then $1 is foo and $2 is bar. Use $@ to refer to all arguments.
Can I make a script that runs at startup?
Yes, but the method varies by distribution. A common way is to place a script in /etc/init.d/ and enable it with update-rc.d, or use a systemd service file. For a simple user-level startup, you can add the script to your desktop's autostart folder (e.g., ~/.config/autostart/).
Is it safe to delete a script after running it?
Yes, unless it's part of a system process. Your own scripts are just files; deleting them has no effect on running processes, but any scheduled tasks (cron) that reference them will fail.