How to Write Your First Bash Script
Shebang, variables, conditionals, and the spacing mistake that confuses beginners.
A Bash script is simply a list of commands saved in a file, to run them all together just by typing its name.
Your first script
#!/bin/bash
echo "Hello, $(whoami)"
echo "Today is $(date +%A)"
Save it as greeting.sh.
The first line (#!/bin/bash) is called a "shebang" —
it tells the system which program should interpret the rest of the
file. Without it, the script might not run correctly depending on how
you invoke it.
Giving it execute permissions
chmod +x greeting.sh
./greeting.sh
Basic variables and conditionals
#!/bin/bash
NAME="Anna"
if [ "$NAME" == "Anna" ]; then
echo "Hello Anna"
else
echo "You're not Anna"
fi
Tip: spacing matters in Bash in ways that surprise
beginners — for example, inside the brackets [ ] of a
conditional, you need a space before and after each bracket, or the
script will fail with a confusing error.
Frequently asked questions
What is the 'shebang' (#!/bin/bash) at the start of the script?
It tells the system which interpreter to use to run the rest of the file. Without this line, the script might not behave as you expect depending on how you invoke it.
Why does my script give an error even though the syntax looks correct?
Check the spacing, especially around brackets in conditionals — Bash is very sensitive to this detail, and one extra or missing space causes errors that can be confusing at first.