🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › Linux/Bash for Web & Software Development › Lesson 6
TEC-WEB46-06 · Lesson 6 · 14 clock hours · lab

Advanced Bash: Input Validation, Error Handling, and Scheduling

Objective. Students will add input validation, exit codes, and cron scheduling to Bash scripts and verify correct behavior under failure conditions.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Why Robust Bash Scripts Matter

A script that works only under perfect conditions is not production-ready. Real servers encounter missing files, wrong arguments, occupied ports, and permission errors every day. A professional Bash script must detect those problems, report them clearly, and exit with a code that other tools can act on. This lesson adds three layers of reliability to your scripts: strict-mode settings, input validation with exit codes, and automated scheduling via cron.

Strict Mode: `set -euo pipefail`

Place this line near the top of every script you write in this program:

```bash

set -euo pipefail

```

Without these options, a script can sail past a failed command and continue doing damage. Together they act like a safety net that stops execution as soon as something goes wrong.

Input Validation and the `usage()` Function

Users and automated callers will sometimes invoke your script incorrectly. Check required arguments at the top of the script and print helpful guidance when they are missing.

```bash

usage() {

echo "Usage: $0 <source_dir> <dest_dir>" >&2

exit 1

}

[[ $# -lt 2 ]] && usage

```

`>&2` redirects the message to standard error so it does not pollute standard output. The script then exits with code `1`, which signals a usage error to whatever called it.

Exit Codes

Every process exits with a number from 0 to 255. The universal convention:

| Code | Meaning |

|------|---------|

| 0 | Success |

| 1 | General or usage error |

| 2 | Misuse of shell built-in |

| Any non-zero | Something failed |

For scripts you write, define specific codes for each failure type and document them in a comment block at the top. For example:

```bash

```

The calling process (another script, a CI/CD pipeline, or cron) can read `$?` immediately after your script runs to decide what to do next.

Logging Errors to a File

A log file gives you a record of what happened and when. A minimal logging pattern:

```bash

LOGFILE="/var/log/deploy_check.log"

log() {

echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOGFILE"

}

log "INFO Script started"

if [[ ! -d "$SOURCE" ]]; then

log "ERROR Source directory $SOURCE not found"

exit 2

fi

log "INFO All checks passed"

```

Note on permissions: `/var/log/` is owned by root on most Linux systems. When running scripts as a non-root user, either use `sudo` carefully, choose a log path your user owns (such as `~/logs/`), or have an administrator pre-create the file with appropriate ownership. Never run a production script as root unless absolutely required — apply the principle of least privilege.

Scheduling with Cron

Cron is the standard Linux job scheduler. Each user has a personal crontab file edited with:

```bash

crontab -e

```

A crontab entry has five time fields followed by the command:

```

0 7 1-5 /home/user/deploy_check.sh >> /home/user/logs/deploy_check.log 2>&1

```

Always use absolute paths in crontab entries. Cron runs with a minimal environment and will not find scripts or interpreters through your interactive `PATH`. Verify entries with `crontab -l`.

Safety Points

Failure Simulation

The best way to verify error handling is to deliberately break things in a controlled way:

1. Remove the file your script expects — confirm a non-zero exit code and a log entry with a timestamp.

2. Bind a port with `nc -l 8080 &` — confirm the port-busy branch fires.

3. Call the script with no arguments — confirm `usage()` prints to stderr and exits with code 1.

Checking `echo $?` immediately after the script exits shows the exit code. Reading the log file with `tail -20 /path/to/logfile` confirms the timestamped entries.

Key terms9

exit codeAn integer (0–255) returned by a process when it finishes; 0 means success and any non-zero value signals an error that calling processes can inspect via $?.
set -euo pipefailA Bash strict-mode directive that stops execution on any unhandled error (-e), treats undefined variables as errors (-u), and propagates pipeline failures (-o pipefail).
crontabA per-user configuration file that schedules commands to run automatically at specified times; edited with the crontab -e command and listed with crontab -l.
cron field syntaxThe five time fields in a crontab entry: minute, hour, day-of-month, month, and day-of-week, each accepting numbers, ranges (1-5), wildcards (*), and step values.
input validationChecking that all required arguments, files, and conditions are present and correct before the main body of a script executes, preventing undefined behavior downstream.
usage() functionA Bash function that prints correct invocation syntax to standard error and exits with a non-zero code when a script is called with missing or invalid arguments.
stderr (standard error)File descriptor 2; the standard output stream reserved for error and diagnostic messages, redirected with >&2 so error text does not mix with normal program output.
least privilegeA security principle stating that a process or user should be granted only the minimum permissions necessary to accomplish its task, reducing the impact of errors or attacks.
pipefailThe Bash shell option that causes a pipeline to return the exit status of the last command in the pipeline that failed, rather than always returning the last command's status.
In class: Instructor demo: extend the backup script from the previous lesson with set -euo pipefail, a usage() function triggered by missing arguments, and logging of errors to /var/log/backup.log. · Lab: students modify their deploy_check.sh to log all outcomes with timestamps to a log file, return appropriate exit codes (0 for success, non-zero for each failure type), and schedule the script to run every weekday at 7 a.m. using crontab -e. · Failure simulation: instructor or lab partner deliberately triggers each failure condition (missing file, occupied port) and students confirm that the log file and exit code reflect the error correctly.
Materials: Student VMs, crontab man page, Bash manual (set built-in section), previous deploy_check.sh script
Check: Instructor reviews crontab entry and runs script under each failure scenario; log entries and exit codes must be correct for all three scenarios — pass requires 3/3.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA Linux+: Scripting, Containers, and Automation
1. A Bash script contains `set -euo pipefail` at the top. A command in the middle of the script returns exit code 1. What happens next?
CompTIA Linux+: Scripting, Containers, and Automation
2. Which crontab entry runs `/home/dev/check.sh` at 7:00 a.m. every weekday (Monday–Friday)?
CompTIA Linux+: Scripting, Containers, and Automation
3. A developer's script prints its error message with `echo "Error: file not found"` but the output does not appear when the calling pipeline captures stdout. What change fixes this?
CompTIA Linux+: Scripting, Containers, and Automation
4. After running `./deploy_check.sh`, a developer types `echo $?` and sees `2`. What does this most likely indicate?
CompTIA Linux+: Scripting, Containers, and Automation
5. Which `set` option causes Bash to treat the use of an undefined variable as an error and exit?
CompTIA Linux+: Scripting, Containers, and Automation
6. A script scheduled in crontab fails silently every morning. The most likely reason is:
CompTIA Linux+: Scripting, Containers, and Automation
7. A `usage()` function inside a Bash script is best triggered by which condition?
CompTIA Linux+: Security
8. Which security practice should be followed when writing a Bash script that runs as a scheduled cron job?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.