Writing Your First Bash Script Step by Step
A Bash script is a plain text file that holds commands you would otherwise type into a terminal one at a time. Once the commands are saved in a file, you can run them again and again, share them with others, and combine them with other tools. That is the whole idea, and it is simpler than it sounds.
This guide walks through a first script from an empty file to something useful. You need a Linux or macOS terminal, or Bash on Windows through WSL or Git Bash. No earlier scripting experience is required.
Create the file and add a shebang
Open any text editor and create a file named hello.sh. The first line of a script should be the shebang, which tells the system which program should run the file.
#!/usr/bin/env bash
echo "Hello from my first script"
The #! pair is read by the operating system, and /usr/bin/env bash finds Bash wherever it is installed. Everything after that is ordinary shell commands. The echo command prints text to the screen.
Make it executable and run it
A new file is not allowed to run as a program until you grant that permission. Use chmod to add the execute bit, then start the script by giving its path.
chmod +x hello.sh
./hello.sh
The ./ part matters. Your shell searches only certain folders for programs, and the current folder is usually not one of them. Writing ./ says "run the file that sits right here." You can also skip the permission step by running bash hello.sh, which passes the file to Bash directly.
Use variables
Variables store values you want to reuse. Assign them with no spaces around the equals sign, and read them with a dollar sign.
#!/usr/bin/env bash
name="Sam"
echo "Hello, $name"
echo "Today is $(date +%A)"
The $(...) form is called command substitution. It runs the command inside the brackets and puts its output into the line. Always wrap variable references in double quotes, as in "$name". Without quotes, a value containing spaces gets split into several words, and that causes many beginner bugs.
Accept arguments
Scripts become far more useful when they accept input from the command line. Bash gives you special variables for this: ${1} is the first argument, ${2} the second, and $# is the count of arguments.
#!/usr/bin/env bash
if [ $# -lt 1 ]; then
echo "Usage: ${0} <name>"
exit 1
fi
echo "Hello, ${1}"
Here ${0} holds the script name, which makes the usage message accurate even if you rename the file. The exit 1 line stops the script and reports failure. By convention, an exit code of 0 means success and anything else means something went wrong.
Make decisions with conditions
The if statement checks a test and runs commands only when it passes. The test goes inside square brackets with spaces on both sides.
file="notes.txt"
if [ -f "$file" ]; then
echo "$file exists"
else
echo "$file is missing"
fi
Some tests worth memorising:
-fis true when a regular file exists.-dis true when a directory exists.-zis true when a string is empty.-eq,-ltand-gtcompare whole numbers.=compares two strings.
Repeat work with loops
A for loop runs the same commands for each item in a list. Combined with a wildcard, it can process many files in one go.
#!/usr/bin/env bash
for file in *.txt; do
echo "Counting lines in $file"
wc -l "$file"
done
A while loop keeps going as long as a condition holds, which is handy for reading a file line by line. Start with for, though. It covers most everyday jobs.
Put it together
Here is a small script that makes a dated backup copy of a folder you name on the command line.
#!/usr/bin/env bash
if [ $# -ne 1 ]; then
echo "Usage: ${0} <folder>"
exit 1
fi
source_dir="${1}"
stamp=$(date +%Y-%m-%d)
target="${source_dir%/}-backup-$stamp"
if [ ! -d "$source_dir" ]; then
echo "Not a folder: $source_dir"
exit 1
fi
cp -r "$source_dir" "$target"
echo "Copied to $target"
Read it slowly. It checks the argument count, builds a name from the date, confirms the folder exists, and only then copies. Checking inputs before doing real work is a habit worth forming early.
Tips for avoiding common mistakes
- Test with harmless commands first. Replace
rmwithecho rmwhile you are learning, so you see what would happen. - Run
bash -n script.shto check syntax without executing anything. - Run
bash -x script.shto print each command as it runs, which shows where things go wrong. - Keep scripts short and single purpose. Small scripts are easier to trust.
- Add comments only where the reason for a line is not obvious.
Frequently Asked Questions
Do I need to end the file name with .sh?
No. The extension is only a hint for people and editors. What makes a file runnable is the execute permission and, for direct execution, a valid shebang line. Many system commands have no extension at all.
What is the difference between Bash and sh?
The sh program is a minimal, older shell standard, while Bash adds many extra features such as arrays and the double bracket test. If your script uses Bash features, start it with a Bash shebang rather than #!/bin/sh.
Why does my script say permission denied?
The file almost certainly lacks the execute bit. Run chmod +x on it and try again. If the error persists, check that you are not trying to run it from a drive or folder mounted with execution disabled.