Your First Script
Prerequisites: Pipes: connecting commands
A script is a text file containing commands. Running it runs every command in order — so you only have to work something out once.
Writing it
Create a file called hello.sh in any text editor (VS Code, nano, vim):
#!/usr/bin/env bash
# My first script
echo "Hello, $USER!"
echo "Today is $(date +%A)."
- The first line, the shebang (
#!), tells the system which program should run the file./usr/bin/env bashfinds Bash wherever it's installed. - Lines starting with
#are comments.
Running it
$ chmod +x hello.sh
$ ./hello.sh
Hello, ada!
Today is Tuesday.
chmod +xmakes the file executable (you only do this once)../hello.shruns it. The./means "in the current directory" — Bash doesn't look in the current directory for commands by default, for safety.
You can also run a script without making it executable: bash hello.sh.
A slightly bigger script
#!/usr/bin/env bash
# Create a dated notes file and list the notes folder.
mkdir -p notes
file="notes/$(date +%Y-%m-%d)-meeting.md"
echo "# Meeting notes" > "$file"
echo "Created $file"
ls notes | wc -l
Each time you run it, it creates a file named after today's date. Scripts like this — a few commands you'd otherwise type by hand — are where most automation starts.
Where to keep scripts
Put personal scripts in a folder such as ~/bin or ~/.local/bin, and
make sure it's in your PATH (add
export PATH="$HOME/.local/bin:$PATH" to ~/.bashrc). Then you can run
them from anywhere by name, without ./.
Common mistakes
Permission denied— the file isn't executable; runchmod +x.bad interpreter: /bin/bash^M— the file has Windows line endings (CRLF). Set your editor to use LF line endings, or convert withdos2unix hello.sh.command not foundwhen typinghello.sh— use./hello.sh.