Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Create a Linux Bash Script: A Practical Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Add commands here
  4. Common Mistakes
  5. Tips
  6. Troubleshooting
  7. Frequently Asked Questions

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, and chmod—but you can follow along even if you're new.

Step-by-Step

  1. 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).
  2. Create a new file with a .sh extension, though the extension is not mandatory. Use nano myscript.sh to open the nano editor.
  3. 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.
  4. 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.
  5. Make the script executable with: chmod +x myscript.sh. This grants execute permission—without it, you'll get a "Permission denied" error.
  6. Run the script from the current directory using: ./myscript.sh. The ./ is required to tell Bash to look in the current directory.
  7. 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.
  8. Use command substitution to capture output. Example: current_dir=$(pwd) then echo "You are in $current_dir".
  9. Accept user input with read: read -p "Enter your name: " user_name then echo "Hi $user_name".
  10. Add loops for repetitive tasks. A simple for loop:
    for file in *.txt; do
      echo "Processing $file"
    

    Add commands here

    done
  11. 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"
  12. Schedule it with cron (optional) to run automatically. Use crontab -e and add a line like 0 2 * * * /home/you/scripts/backup.sh to 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 be name="John".
  • Missing quotes around variables—especially when paths contain spaces. Always use "$var" unless you intentionally want word splitting.
  • Running the script with sh instead of bash—sh may point to dash on some systems, which lacks Bash features. Use ./script.sh or bash script.sh.
  • Using Windows line endings—if you edit on Windows, the \r characters can cause errors. Convert with dos2unix script.sh.

Tips

  • Start simple—write one command at a time and test before adding complexity.
  • Use set -e at 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 echo statements 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 ~/scripts and add that folder to your PATH if you want to run them from anywhere.
  • Check for existing tools—many tasks already have commands like rsync for backups or ffmpeg for media; your script can simply call them.

Troubleshooting

  1. Script won't run: "Permission denied"—Run chmod +x script.sh to add execute permission.
  2. Script runs but does nothing—Check for typos in commands, and run bash -x script.sh to trace each line as it executes.
  3. "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.
  4. Variables not expanding—Ensure you used $VAR or ${VAR}, not VAR alone, and that the variable is defined before use.
  5. Unexpected line endings—If you see \r in error messages, run sed -i 's/\r$//' script.sh or dos2unix.
  6. 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 like HOME at the top of the script if needed.
  7. 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.