🚧 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 › Data Management / Database Administration › Bash Automation for Database Administration › Lesson 2
TEC-DATA86-09 · Lesson 2 · 12 clock hours · demo

Script Structure, Variables, and Control Flow

Objective. Students will construct well-structured Bash scripts that use shebang lines, comments, named variables, positional parameters, if/elif/else logic, and for/while loops to carry out a branching DBA workflow.

⚠ 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 Script Structure Matters for DBAs

As a database administrator, you will repeat the same checks dozens of times a week: Is this server reachable? Does this database exist? How many connections are active? Writing those checks by hand every time wastes time and introduces human error. A well-structured Bash script turns a ten-step manual procedure into a single command that runs the same way every time. That consistency is what employers expect and what the credentials you are working toward reward.

The Shebang Line

Every Bash script must begin with a shebang line:

```bash

#!/usr/bin/env bash

```

This line tells the operating system which interpreter to use. Without it, the shell may run your script under a different interpreter (sh, dash, etc.) that does not support all Bash features. The `env bash` form finds Bash wherever it lives on the system, making the script more portable across Linux distributions — important when you manage servers at multiple sites.

Always place the shebang on line 1, column 1, with no leading spaces.

Comments

Comments begin with `#` and are ignored by the interpreter. Use them to explain why the script does something, not just what it does. At minimum, every script should have a header block:

```bash

#!/usr/bin/env bash

```

Inline comments after code are fine: `psql -lqt # list databases, quiet, tuples only`

Variables and Positional Parameters

A variable stores a value you want to reuse. Name it in UPPER_CASE by convention for environment-level or script-wide values:

```bash

LOG_FILE="/var/log/db_status.log"

MIN_CONNS=5

```

Assign with `=` and no spaces around the equals sign. Reference with a leading `$`, and always double-quote the reference to prevent word-splitting on values that contain spaces:

```bash

echo "Log is at: $LOG_FILE"

```

Positional parameters are arguments passed on the command line. `$1` is the first argument, `$2` the second, `$0` is the script name. Use `$#` to check how many arguments were supplied:

```bash

if [[ $# -lt 1 ]]; then

echo "Usage: $0 <database_name>" >&2

exit 1

fi

DB_NAME="$1"

```

Redirecting the error message to `>&2` (standard error) is correct practice — it keeps error output separate from normal output and makes pipelines behave predictably.

if / elif / else Logic

Bash uses double brackets `[[ ]]` for conditional tests. Common operators:

Structure:

```bash

if [[ condition_one ]]; then

elif [[ condition_two ]]; then

else

fi

```

Always close with `fi`. Each branch should either produce output or set an exit code.

for and while Loops

A for loop iterates over a list:

```bash

for HOST in $(cat servers.txt); do

ping -c 1 -W 2 "$HOST" &>/dev/null && STATUS="UP" || STATUS="DOWN"

echo "$(date '+%Y-%m-%d %H:%M:%S') $HOST $STATUS" >> "$LOG_FILE"

done

```

A while loop runs as long as a condition is true, useful for reading a file line by line safely:

```bash

while IFS= read -r HOST; do

done < servers.txt

```

The `while read` pattern is preferred over `for $(cat ...)` when hostnames might contain spaces or special characters.

Exit Codes

Every command returns an exit code: 0 means success, anything else means failure. Your script should return a meaningful exit code with `exit 0` on success and `exit 1` (or higher) on failure. Tools like monitoring systems and CI pipelines rely on these codes to determine whether a job succeeded.

Syntax Checking with bash --norc -n

Before running any script on a production database server, check its syntax:

```bash

bash --norc -n check_db.sh

```

The `-n` flag parses the script without executing it. `--norc` prevents your personal `.bashrc` from interfering. A clean check produces no output. Any error is printed with a line number — fix it, recheck, and document the change in your lab journal. This is a low-risk habit that prevents embarrassing (and potentially damaging) script errors on live systems.

Safety Notes

Scripts that connect to databases carry real risk. Follow these rules:

Good scripting habits are not just about efficiency — they are the first line of defense for the systems you are responsible for protecting.

Key terms8

Shebang lineThe first line of a script (#!/usr/bin/env bash) that tells the OS which interpreter to execute the file.
Positional parameterA variable automatically set by Bash to hold command-line arguments; $1 is the first argument, $2 the second, and so on.
Exit codeAn integer returned by a command or script when it finishes; 0 indicates success, any non-zero value indicates an error condition.
Double-bracket test [[ ]]A Bash-specific conditional construct that evaluates expressions for use in if statements; more robust than single brackets for string comparisons.
Word splittingThe process by which Bash splits an unquoted variable's value on whitespace; double-quoting variables prevents unexpected splitting.
Standard error (stderr)The output stream (file descriptor 2) reserved for error and diagnostic messages; redirected with >&2 so error output stays separate from normal output.
Syntax check (-n flag)Running bash -n on a script parses it for syntax errors without executing any commands, allowing safe pre-flight validation.
IFS (Internal Field Separator)A Bash variable that determines how the shell splits input into fields; setting IFS= before read -r preserves lines exactly as they appear, including leading spaces.
In class: Instructor live-codes a script that accepts a database name as a positional parameter, checks whether that database exists using psql -lqt, and echoes a pass/fail message; students follow along, then modify the script to also check for a minimum connection count. · Students write an original 30-line script that loops through a text file of five server hostnames, pings each, and writes 'UP' or 'DOWN' with a timestamp to a status log file; peer-pairs review each other's scripts against a six-point checklist (shebang, comments, quoting, exit code, loop, log). · Run bash --norc -n on each script to check syntax, fix any errors reported, and document the before/after diff in the lab journal.
Materials: Linux VM, psql client, text editor (VS Code or vim), bash manual pages, peer-review checklist handout
Check: Script must pass bash --norc -n with zero errors, correctly branch on all three test conditions, and receive at least 5 of 6 on the peer checklist; instructor spot-checks one script per pair.

Practice check8

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

Shell scripting fundamentals / automation
1. A DBA writes a Bash script but omits the shebang line. What is the most likely consequence on a Linux system that defaults to dash as /bin/sh?
Shell scripting / quality assurance
2. Which command checks a Bash script for syntax errors without executing any of its commands?
Shell scripting / data integrity
3. A script line reads: echo $DB_NAME. A DBA passes the value 'my database' (with a space) as the first argument. What problem does the missing double-quote cause?
Shell scripting / operational best practices
4. In a DBA automation script, error messages should be redirected to standard error (>&2) rather than standard output. Why?
Shell scripting / automation reliability
5. A script loops through a file of server hostnames and must handle names that might contain leading spaces. Which loop construct handles this most safely?
PostgreSQL administration / scripting
6. A PostgreSQL DBA script must verify that a database named $DB_NAME exists before attempting a backup. Which psql invocation is conventionally used to list existing databases in a machine-parsable form?
Shell scripting fundamentals
7. Which of the following variable assignment lines is syntactically correct in Bash?
Database security / operational best practices
8. A trainee DBA stores a database password directly in a Bash script as PASSWORD='s3cr3t'. An instructor flags this as a security risk. What is the recommended alternative?
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.