Bash Scripting Basics
Your First Bash Script
A Bash script is a plain text file containing commands, with a special first line that tells the system which interpreter to use.
Create your first script
nano hello.sh
Type the following, then save and exit (Ctrl+O, Ctrl+X in nano):
#!/bin/bash
echo "Hello, world!"
echo "Today is $(date +%A)"
- The first line
#!/bin/bashis the shebang — it tells Linux to run this file with the Bash interpreter echoprints text$(...)runs a command and inserts its output — here,date +%Aprints the current weekday
Make it executable
A script will not run just because it is a text file. Give it the execute bit you learned about in the permissions tutorial:
chmod +x hello.sh
Run it
./hello.sh
`./hello.sh`, not `hello.sh`
The ./ tells Bash to look for the script in the current directory. Your shell only searches its PATH (like /usr/bin) for bare command names — so hello.sh alone will usually fail with "command not found".
Alternative: run it with bash
You can also run any script without making it executable by passing it to Bash directly:
bash hello.sh
Add a comment
# starts a comment — anything after it is ignored:
#!/bin/bash
# This is my first script
echo "Hello, world!"
Try it
- Create
hello.shexactly as above chmod +x hello.sh && ./hello.sh- Change the
datecommand and run it again
Advertisement