🚧 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 1
TEC-DATA86-09 · Lesson 1 · 10 clock hours · theory

Linux Shell Foundations and the DBA Command Line

Objective. Students will identify and correctly use fundamental Bash constructs—variables, quoting rules, command substitution, pipelines, and redirections—as the building blocks of all subsequent DBA automation.

⚠ 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 the Command Line Matters to a DBA

Database administrators spend a large portion of every workday at the terminal. Whether you are checking which PostgreSQL processes are consuming memory, rotating log files, or scheduling a nightly backup, the Linux shell is your control panel. This lesson builds the Bash foundation that every automation script you write later will depend on. Accuracy matters here: a misplaced quote or a forgotten redirect can corrupt data or overwrite a file you needed.

The Linux Shell and Bash

Bash (Bourne Again SHell) is the default interactive shell on most Linux distributions, including CentOS and Ubuntu. When you open a terminal, Bash reads your commands, interprets them, and passes instructions to the Linux kernel. Every DBA automation script in this course is a plain text file of Bash commands saved with a `.sh` extension and executed by the Bash interpreter.

Bash reads commands from left to right. Before executing anything, it performs a set of expansions in a defined order: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion. Understanding this order prevents hard-to-find bugs.

Variables

A variable stores a value for later use. Assignment uses no spaces around the equals sign:

```bash

DB_HOST=localhost

DB_PORT=5432

```

Retrieve the value by prefixing the name with `$`:

```bash

echo $DB_HOST

echo "Connecting to ${DB_HOST}:${DB_PORT}"

```

Braces around the name (`${DB_HOST}`) are optional when the variable name is unambiguous, but they are considered best practice because they prevent accidental concatenation with adjacent characters. Variable names are case-sensitive; by convention, environment and configuration variables are written in ALL_CAPS, while loop counters use lowercase.

Quoting Rules

Quoting controls which characters Bash interprets and which it treats as literal text. There are three quoting mechanisms:

A common DBA mistake is forgetting to quote a variable that contains spaces, causing a filename or connection string to be split into multiple arguments. Always quote variables that may contain whitespace: `"$DB_NAME"`.

Command Substitution

Command substitution runs a command and inserts its output inline. The preferred modern syntax uses `$(...)` rather than backticks, because it nests cleanly:

```bash

CURRENT_DATE=$(date +%Y-%m-%d)

echo "Backup started on $CURRENT_DATE"

```

DBAs use command substitution to capture dynamic values—row counts, process IDs, or timestamps—directly into variables without writing intermediate files.

Pipelines

A pipeline connects commands so the standard output (stdout) of one command becomes the standard input (stdin) of the next, using the pipe character `|`:

```bash

ps aux | grep postgres | grep -v grep

```

This lists all running processes (`ps aux`), filters for lines containing "postgres," and then removes the grep process itself from the results. Pipelines are fundamental to DBA work: they let you filter, sort, count, and transform data streams without writing temporary files.

Redirections

Redirection changes where a command reads from or writes to:

| Operator | Meaning |

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

| `>` | Write stdout to a file, overwriting it |

| `>>` | Append stdout to a file |

| `<` | Read stdin from a file |

| `2>` | Redirect stderr (error output) to a file |

| `2>&1` | Merge stderr into stdout |

Example: saving a PostgreSQL query log and capturing errors separately:

```bash

psql -U postgres -c "SELECT count(*) FROM pg_stat_activity;" > query_out.txt 2> query_err.txt

```

Overwriting a file with `>` is irreversible on most filesystems. Before using `>`, confirm you do not need the existing content; use `>>` to append when in doubt.

Safety at the Terminal

The Linux command line operates with the permissions of the logged-in user. Running database administration tasks as the `root` user or the `postgres` superuser without need is risky: a typo in a destructive command has immediate effect. Follow the principle of least privilege—use a regular OS account and `sudo` only for tasks that require elevated permissions, and only for the specific command needed. Before running any command that modifies or deletes data, test it in a non-production environment. When writing scripts that will run as scheduled jobs, store credentials in environment variables or a secured configuration file, never hard-coded in the script itself.

Navigating the Filesystem and Inspecting Processes

Key navigation commands every DBA uses daily:

Process inspection:

Putting It Together

Every DBA automation script—backup jobs, health checks, log rotation—is assembled from exactly these building blocks: variables that hold configuration, quoting that protects string values, command substitution that captures live data, pipelines that transform output, and redirections that preserve logs. Mastering these fundamentals now means every script you write in the remaining modules will be readable, reliable, and maintainable.

Key terms9

BashBourne Again SHell; the default command interpreter on most Linux systems, used to run interactive commands and automation scripts.
VariableA named storage location in Bash that holds a string value; referenced with a leading dollar sign (e.g., $DB_HOST).
QuotingThe use of single quotes, double quotes, or backslashes to control which characters Bash interprets literally versus as special syntax.
Command SubstitutionThe $(…) syntax that executes a command and replaces the expression with the command's output, allowing dynamic values to be stored in variables.
PipelineA sequence of commands connected by the | operator, where the stdout of each command is passed as stdin to the next command.
RedirectionOperators such as >, >>, <, and 2> that change the source or destination of a command's input or output streams.
Standard Output (stdout)The default output stream (file descriptor 1) where a command writes its normal results; can be redirected with > or >>.
Standard Error (stderr)The separate output stream (file descriptor 2) where commands write error and diagnostic messages; redirected with 2>.
Principle of Least PrivilegeThe security practice of granting only the minimum permissions needed to perform a specific task, reducing risk from errors or misuse.
In class: Read sections 1–4 of the GNU Bash Reference Manual (freely available at gnu.org); annotate five constructs not encountered before and share annotations in a whole-class discussion. · Complete 20 progressive command-line exercises on a CentOS or Ubuntu VM—navigating the filesystem, inspecting processes with ps and top, managing files, and chaining commands with pipes—recording each command and its output in a lab journal. · As an exit activity, write a one-page 'DBA command cheat sheet' that maps ten common administrative tasks (e.g., list running Postgres connections) to their shell commands, which the instructor reviews for accuracy.
Materials: Linux VM (VirtualBox or cloud instance), GNU Bash Reference Manual (gnu.org), terminal emulator, lab journal template
Check: Instructor reviews lab journal entries; student must answer correctly at least 8 of 10 spot-check questions on quoting rules, pipe behavior, and redirect syntax to pass this lesson checkpoint.

Practice check8

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

Shell scripting and automation
1. A DBA writes the line `BACKUP_DIR=/mnt/backups` in a script. What is the correct way to reference that variable later in the same script?
Shell scripting and automation
2. Which quoting style in Bash preserves every character literally, preventing variable expansion and command substitution?
Shell scripting and automation
3. A DBA runs: `psql -U postgres -c "SELECT now();" > result.txt`. What happens to the file result.txt if it already exists and contains data?
Shell scripting and automation
4. What does the following pipeline do? `ps aux | grep postgres | grep -v grep`
Shell scripting and automation
5. Which command substitution syntax is preferred in modern Bash scripts because it supports clean nesting?
Shell scripting and automation
6. A DBA wants to redirect both standard output and standard error from a backup script to a single log file. Which redirect syntax achieves this?
Database security and administration
7. According to the principle of least privilege, which practice is safest when running database administration scripts on a Linux server?
Shell scripting and automation
8. A DBA stores a database name in a variable: `DB='my database'`. The script later runs `psql -d $DB`. What problem occurs, and how is it fixed?
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.