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.

Mar 21, 2025 - 09:53
Updated: 
103.8k

Linux Administration in IT Infrastructure · Commands & reference

Bash Scripting for Beginners: Safe Automation With Practical Examples

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?

#!/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?

OptionEffectLimit
-eExit when a command failsIgnored inside if tests and parts of and-or lists
-uTreat unset variables as errorsUse ${var:-} where a variable may be empty
-o pipefailA pipeline fails if any part failsCommands 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?

FeatureExample
Testif [[ -f "$path" ]]; then ...; fi
Loop over filesfor f in /var/log/*.log; do ...; done
Read lineswhile IFS= read -r line; do ...; done < file
Arrayhosts=(web1 web2); for h in "${hosts[@]}"; do ...; done
Functionbackup() { local src="$1"; ...; }
Command outputtoday="$(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

Use #!/usr/bin/env bash or #!/bin/bash. The shebang tells the system to run the file with Bash rather than another shell.

It exits on most command failures, treats unset variables as errors, and makes a pipeline fail when any command inside it fails.

No. It is ignored inside if conditions, while tests and parts of and-or lists, so important results still need explicit checks in the script.

Unquoted variables are split on spaces and expanded as wildcards, which breaks file names with spaces and can delete or touch the wrong files.

ShellCheck is a free static analysis tool for shell scripts. It points out quoting mistakes, syntax problems and risky patterns before you run a script.

eval runs its argument as code. If any part comes from user input, an attacker can inject extra commands, which is OS command injection.

Create them with mktemp and register a trap on EXIT that removes them, so cleanup happens even when the script fails part way through.

No. sh means a POSIX shell, which lacks Bash features such as arrays and the double bracket test. Run Bash scripts with Bash.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.