Bash Scripting for Beginners: Safe Automation With Practical Examples
A Bash script is a text file of shell commands that runs from top to bottom. To write scripts that are safe and predictable, start with a #!/usr/bin/env bash line, add set -euo pipefail so errors and unset variables stop the script, quote every variable expansion, use functions and local variables, and clean up temporary files with trap. Check every script with ShellCheck before running it.
Topic: Linux Administration in IT Infrastructure · Commands & reference
Quick answer: A Bash script is a text file of shell commands that runs from top to bottom. To write scripts that are safe and predictable, start with a #!/usr/bin/env bash line, add set -euo pipefail so errors and unset variables stop the script, quote every variable expansion, use functions and local variables, and clean up temporary files with trap. Check every script with ShellCheck before running it. Avoid eval and never pass untrusted input into commands, because that is how command injection happens. These habits turn quick one-liners into automation you can trust on real servers.
Key takeaways
- Use set -euo pipefail, but know it does not catch every error.
- Quote variables as "$var" to stop word splitting and globbing.
- Use arrays for lists of file names, not space-separated strings.
- Create temporary files with mktemp and remove them in a trap.
- Run ShellCheck on every script before use.
Table of Contents
- How Do You Write and Run Your First Script?
- What Does set -euo pipefail Do?
- Why Does Quoting Matter So Much?
- Which Building Blocks Should You Learn?
- What Does a Practical Script Look Like?
- How Do You Keep Scripts Secure?
- How Does ShellCheck Help?
- References
How Do You Write and Run Your First Script?
#!/usr/bin/env bash
set -euo pipefail
name="${1:-world}"
echo "Hello, ${name}"
Save it as hello.sh, then run chmod +x hello.sh and ./hello.sh Priya. The ${1:-world} form uses a default when no argument is given. The GNU Bash Reference Manual documents every expansion.
What Does set -euo pipefail Do?
| Option | Effect | Limit |
|---|---|---|
| -e | Exit when a command fails | Ignored inside if tests and parts of and-or lists |
| -u | Treat unset variables as errors | Use ${var:-} where a variable may be empty |
| -o pipefail | A pipeline fails if any part fails | Commands like grep return 1 when nothing matches |
The set builtin page lists the cases where -e does not trigger, so still check important results explicitly.
Why Does Quoting Matter So Much?
Unquoted variables are split on spaces and expanded as wildcards. A file named my report.txt becomes two arguments, and a value of * becomes every file in the folder. Compare:
file="my report.txt"
rm $file # wrong: tries to remove my and report.txt
rm -- "$file" # right: removes exactly one file
ShellCheck flags this as SC2086.
Which Building Blocks Should You Learn?
| Feature | Example |
|---|---|
| Test | if [[ -f "$path" ]]; then ...; fi |
| Loop over files | for f in /var/log/*.log; do ...; done |
| Read lines | while IFS= read -r line; do ...; done < file |
| Array | hosts=(web1 web2); for h in "${hosts[@]}"; do ...; done |
| Function | backup() { local src="$1"; ...; } |
| Command output | today="$(date +%F)" |
What Does a Practical Script Look Like?
This script reports disk use above a threshold and cleans up after itself:
#!/usr/bin/env bash
set -euo pipefail
threshold="${1:-80}"
tmp="$(mktemp)"
trap 'rm -f -- "$tmp"' EXIT
df -P --exclude-type=tmpfs | tail -n +2 > "$tmp"
while read -r fs _ _ _ use mount; do
pct="${use%\%}"
if (( pct >= threshold )); then
echo "WARNING: ${mount} on ${fs} is at ${pct}%"
fi
done < "$tmp"
The trap removes the temporary file even when the script fails, and ${use%\%} strips the trailing percent sign.
How Do You Keep Scripts Secure?
- Never use eval on user input; it turns data into code. This is CWE-78, explained by OWASP.
- Validate inputs, for example with [[ $threshold =~ ^[0-9]+$ ]].
- Use -- before file arguments so names starting with a dash are not read as options.
- Keep secrets out of scripts and command lines, where ps and history can expose them.
- Use full paths for important commands in root cron jobs.
If a script must run in sh, follow the POSIX shell specification, since [[ ]] and arrays are Bash features.
How Does ShellCheck Help?
ShellCheck is a static analyser that finds quoting bugs, unused variables and risky patterns. Install it with apt or dnf and run shellcheck script.sh. Our shell scripting introduction covers the basics, and the most useful Linux commands give you more to automate. For guided projects, see our Linux and scripting training.
References
Frequently Asked Questions
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0