Audit and Harden Production Shell Snippets

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

While auditing deployment and maintenance tooling on a Linux server fleet, you come across two Bash one-liners embedded in automation scripts:

Command 1 (stopping a worker service):

ps aux | grep my_worker | awk '{print $2}' | xargs kill -9

Command 2 (fixing directory modes and launching a database migration):

chmod -R 777 $DEPLOY_DIR && ./bin/migrate --env=$ENV 2>&1 > /dev/null &

Walk through both commands as an infrastructure engineer:

  1. Execution trace and failure modes: Explain what the shell and OS kernel actually do when running each one-liner, and pinpoint at least three concrete bugs, race conditions, or security hazards per command.
  2. Production-grade rewrites: Write clean, idiomatic Bash replacements for both commands:
    • Your Command 1 rewrite must signal only genuine my_worker processes (never hitting the lookup tool itself or bystander commands whose name or arguments merely contain my_worker, such as my_worker_watchdog.py), exit cleanly with status 0 when nothing is running, and give workers a bounded window to shut down cleanly before resorting to a hard kill.
    • Your Command 2 rewrite must apply least-privilege file modes instead of world-writable permissions, defend against whitespace or special characters in variables, abort before starting ./bin/migrate whenever changing directory permissions fails, capture both standard output and standard error in a log file, and record or track the migration process ID and exit status.

Scope & Expectations

  • Accurate shell & OS mechanics: Trace pipeline concurrency, variable expansion, operator precedence between && and &, and left-to-right file-descriptor binding rather than hand-waving what the commands "probably" do.
  • Concrete hazard diagnosis: Surface at least three distinct failure modes per snippet spanning process matching, signal semantics, empty-input handling, filesystem security, quoting, and lost exit codes or logs.
  • Defensive, idiomatic Bash: Produce self-contained replacements that handle zero-match, space-in-path, timeout, and permission-error edge cases cleanly without introducing new races or silent failures.

Step-by-step walkthrough

  1. Trace Command 1 stage by stage

    ps aux | grep my_worker | awk '{print $2}' | xargs kill -9
    

    When bash sees a pipeline (commands joined by |, where each command's standard output streams into the next command's standard input), it starts all four processes concurrently, not one after another:

    Stage 1: ps aux             Snapshots every process across all users on the machine:
                                USER  PID  %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
    Stage 2: grep my_worker     Keeps any line containing the substring "my_worker" anywhere
    Stage 3: awk '{print $2}'   Splits each matching line on whitespace and prints column 2,
                                the PID (process identifier: integer ID assigned by the kernel)
    Stage 4: xargs kill -9      Reads all PIDs until stdin closes, then runs:
                                kill -9 PID_1 PID_2 ...
    

    Trace a concrete process table at the instant ps aux reads /proc:

    USER   PID    ...  COMMAND
    app    4101   ...  /opt/app/my_worker --queue=gpu
    app    4102   ...  python3 my_worker_watchdog.py
    app    4103   ...  tail -f /var/log/my_worker.log
    app    4230   ...  grep my_worker
    

    grep matches all four lines, awk emits 4101 4102 4103 4230, and xargs executes kill -9 4101 4102 4103 4230: - Only PID 4101 was the intended worker. Both the watchdog (4102) and an engineer's log viewer (4103) are killed immediately as collateral damage. - Because xargs waits for stdin to close before invoking kill, grep (PID 4230) has usually already finished and exited. kill prints No such process for 4230 and exits 1, which makes GNU xargs exit with status 123—marking the cleanup job as failed even though the worker died!

  2. Identify every pitfall in Command 1

    1. Unbounded substring matching: grep my_worker searches the entire formatted ps line—matching my_worker_watchdog.py, vim my_worker.py, tail -f my_worker.log, a Linux user named my_worker_bot, or even the parent deployment script if my_worker appears in bash -c "... my_worker ..." (causing the script to kill itself mid-run!).
    2. Self-matching pipeline race: Because ps and grep my_worker launch in parallel, grep unpredictably captures its own process row depending on kernel scheduling, making exit codes flaky.
    3. TOCTOU / PID recycling race: TOCTOU (time-of-check to time-of-use, a race condition where system state changes between inspecting a resource and acting on it) affects PIDs because ps only takes a point-in-time snapshot. If a worker exits right after ps reads it and the kernel wraps its PID counter around /proc/sys/kernel/pid_max, kill -9 can hit a brand-new, unrelated process.
    4. Zero-match failure on GNU xargs: When zero lines match, GNU xargs (the Linux default) still executes kill -9 once with no PID arguments unless -r (--no-run-if-empty) is passed. kill prints a usage error and exits non-zero (xargs exits 123).
    5. Immediate SIGKILL (-9) instead of graceful SIGTERM (-15): SIGKILL (signal 9) is enforced directly by the OS kernel and cannot be caught, so the worker vanishes mid-instruction—corrupting half-written files, abandoning database transactions or locks, dropping in-flight jobs, and leaving child subprocesses orphaned (reparented to PID 1 and still running). SIGTERM (signal 15) asks the process to shut down cleanly and should always be sent first, escalating to SIGKILL only after a timeout.
    6. Cross-user blast radius and masked pipeline errors: ps aux lists every user's processes (dangerous when run as root), and without set -o pipefail, bash ignores failures in ps, grep, or awk and reports only xargs's exit status.
  3. Build the hardened replacement for Command 1

    Each piece of the replacement directly eliminates one class of bug: - pgrep -u "$owner" -x "$name": Queries the OS process table directly without spawning a text pipeline, never matches pgrep itself, restricts matches to $owner, and with -x requires an exact whole-name match (on Linux, the 15-character kernel comm name), so my_worker_watchdog is never touched. - Clean no-op on zero matches: mapfile -t reads matching PIDs into a bash array; if the array length is 0, the script logs that nothing is running and exits 0. - Two-phase graceful shutdown with identity re-verification: Send SIGTERM, then poll every second using bash's built-in SECONDS counter up to grace_seconds. Crucially, still_running re-queries pgrep -u "$owner" -x "$name" on every check—including right before SIGKILL—so if an original PID exited and was recycled by an unrelated process (or a supervisor spawned a fresh worker under a new PID), SIGKILL will not touch it.

    #!/usr/bin/env bash
    # Requires Linux procps pgrep and bash >= 4 (for mapfile).
    set -euo pipefail
    
    name="my_worker"
    owner="$(id -u)"
    grace_seconds="${GRACE_SECONDS:-30}"
    
    find_pids() {
      # -u scopes to one UID; -x demands an exact process-name match; pgrep never matches itself.
      pgrep -u "$owner" -x "$name" || true
    }
    
    # Filter "$@" down to original PIDs that are STILL alive with the exact process name $name.
    still_running() {
      local current pid
      current="$(find_pids)"
      for pid in "$@"; do
        if grep -Fqx "$pid" <<< "$current"; then
          printf '%s\n' "$pid"
        fi
      done
    }
    
    mapfile -t pids < <(find_pids)
    if (( ${#pids[@]} == 0 )); then
      echo "no $name processes running; nothing to stop" >&2
      exit 0
    fi
    
    echo "sending SIGTERM to $name PIDs: ${pids[*]}" >&2
    kill -TERM "${pids[@]}" 2>/dev/null || true
    
    deadline=$(( SECONDS + grace_seconds ))
    while true; do
      mapfile -t pids < <(still_running "${pids[@]}")
      if (( ${#pids[@]} == 0 )); then
        echo "all $name processes exited cleanly" >&2
        exit 0
      fi
      if (( SECONDS >= deadline )); then
        break
      fi
      sleep 1
    done
    
    echo "grace period (${grace_seconds}s) expired; sending SIGKILL to: ${pids[*]}" >&2
    kill -KILL "${pids[@]}" 2>/dev/null || true
    

    Note on interpreted workers: If the worker is launched via python3 /opt/app/my_worker.py (or #!/usr/bin/env python3), its kernel process name is python3, not my_worker (also note Linux truncates comm at 15 characters). In that case, anchor against the full command line with pgrep -u "$owner" -fx 'python3 /opt/app/my_worker\.py( .*)?'—or better yet in production, manage the worker under systemd or a container supervisor so systemctl stop signals the service's isolated cgroup (a Linux kernel group tracking a service and all its descendants) without scanning PIDs at all.

  4. Trace Command 2: operator precedence and stream redirection

    chmod -R 777 $DEPLOY_DIR && ./bin/migrate --env=$ENV 2>&1 > /dev/null &
    

    Two shell grammar rules surprise almost everyone reading this line quickly:

    1. && binds tighter than &: The trailing & does not background only ./bin/migrate—it backgrounds the entire && chain inside a subshell! The parent script immediately moves on before chmod has even started:

    What the author probably thought:
      chmod -R 777 $DEPLOY_DIR  &&  ( ./bin/migrate --env=$ENV ... & )
    
    What bash actually executes:
      { chmod -R 777 $DEPLOY_DIR && ./bin/migrate --env=$ENV 2>&1 > /dev/null ; } &
    

    2. Redirections execute strictly left to right: Every process starts with file descriptors (integer handles pointing to open I/O streams: 1 for standard output, 2 for standard error). Watch where fd 1 and fd 2 point at each step of 2>&1 > /dev/null:

    Before redirections:      fd 1 (stdout) ---> terminal
                              fd 2 (stderr) ---> terminal
    
    Step 1:  2>&1             fd 1 (stdout) ---> terminal
    ("copy fd 1's target      fd 2 (stderr) ---> terminal   (still the terminal!)
      into fd 2")
    
    Step 2:  > /dev/null      fd 1 (stdout) ---> /dev/null  (stdout discarded!)
    ("point fd 1 at           fd 2 (stderr) ---> terminal   (stderr NOT redirected!)
      /dev/null")
    

    To send both streams into $log_file, you must point fd 1 at $log_file first, and only then copy fd 1 into fd 2: >>"$log_file" 2>&1.

  5. Identify every pitfall in Command 2

    1. World-writable 777 permissions (rwxrwxrwx): Octal 777 grants read, write, and execute rights on every file and directory to every local user and service on the host, violating the principle of least privilege (granting only the minimum permissions required to function). Any compromised low-privilege account can read secret .env files or inject code into ./bin/migrate before it runs! It also marks plain text and config files executable.
    2. Unquoted $DEPLOY_DIR and $ENV: Unquoted variables undergo word splitting (breaking on spaces/tabs/newlines) and glob expansion (expanding wildcards like * or ?). If DEPLOY_DIR="/srv/release v2", bash runs chmod -R 777 /srv/release v2—opening up an unrelated /srv/release directory if one exists! If ENV is empty, --env= silently runs against whatever default environment migrate picks.
    3. Backwards redirection (2>&1 > /dev/null) and lost logs: Standard output is thrown away into /dev/null while standard error spills onto the caller's console instead of a persistent migration log.
    4. Backgrounded chmod and untracked job status: Because & wraps the whole && list and $! (the PID of the most recently backgrounded job) is never saved or waited on, the parent script cannot tell if chmod failed, cannot track migrate while it runs, and exits 0 even when the migration crashes.
    5. Working-directory mismatch: ./bin/migrate resolves relative to wherever the caller happened to stand ($PWD), not $DEPLOY_DIR/bin/migrate.
    6. Shell variable collision: ENV is a special POSIX shell variable read during interactive startup; production scripts prefer APP_ENV or DEPLOY_ENV (we keep ENV below only to preserve the snippet's input contract).
  6. Build the hardened replacement for Command 2

    To satisfy every requirement cleanly: - Validate inputs up front: Enable set -euo pipefail, set umask 027 (a default permission mask ensuring newly created log and PID files are never world-readable or group-writable), reject unset or empty variables via ${VAR:?}, validate ENV against an allowlist, and cd -- "$DEPLOY_DIR" (-- prevents paths starting with - from being parsed as flags). - Run least-privilege chmod synchronously in the foreground: chmod -R -- u=rwX,g=rX,o= . gives owner read/write, group read, and others zero access. Capital X grants execute permission only to directories (needed to enter them) and to files that already had an execute bit (like bin/migrate), leaving config files non-executable. Because chmod runs in the foreground under set -e, any permission failure aborts immediately before ./bin/migrate can ever launch. - Log both streams and track $!: Redirect with >>"$log_file" 2>&1 &, immediately save migrate_pid=$! to a .pid file, and wait "$migrate_pid" so failures propagate accurately.

    #!/usr/bin/env bash
    set -euo pipefail
    umask 027
    
    : "${DEPLOY_DIR:?DEPLOY_DIR must be set and non-empty}"
    : "${ENV:?ENV must be set and non-empty}"
    
    case "$ENV" in
      dev|staging|production) ;;
      *) echo "invalid ENV value: $ENV" >&2; exit 1 ;;
    esac
    
    if [[ ! -d "$DEPLOY_DIR" ]]; then
      echo "deploy directory does not exist: $DEPLOY_DIR" >&2
      exit 1
    fi
    cd -- "$DEPLOY_DIR"
    
    # Foreground step: if chmod fails, set -e aborts immediately and migrate never starts.
    # Capital X sets +x only on directories and already-executable files (such as bin/migrate).
    chmod -R -- u=rwX,g=rX,o= .
    
    log_dir="${LOG_DIR:-$PWD/logs}"
    mkdir -p -- "$log_dir"
    log_file="$log_dir/migrate-$(date +%Y%m%dT%H%M%S).log"
    
    ./bin/migrate --env="$ENV" >>"$log_file" 2>&1 &
    migrate_pid=$!
    printf '%s\n' "$migrate_pid" > "$log_dir/migrate.pid"
    echo "started migration (pid=$migrate_pid), logging to $log_file" >&2
    
    if wait "$migrate_pid"; then
      echo "migration completed successfully" >&2
    else
      status=$?
      echo "migration failed with exit code $status; inspect $log_file" >&2
      exit "$status"
    fi
    

    If the caller truly needs fire-and-forget detachment (returning immediately while monitoring externally), omit the final wait block and have the background subshell write its own exit code atomically once migrate finishes (using && status=0 || status=$? so inherited set -e does not skip writing non-zero statuses):

    { ./bin/migrate --env="$ENV" && status=0 || status=$?
      printf '%s\n' "$status" > "$log_dir/migrate.status"; } >>"$log_file" 2>&1 &
    migrate_pid=$!
    printf '%s\n' "$migrate_pid" > "$log_dir/migrate.pid"
    
  7. Verify both hardened scripts against adversarial cases

    When reviewing infrastructure shell scripts, test the failure paths explicitly rather than only the sunny path:

    • Command 1 checks: Launch two my_worker processes alongside my_worker_watchdog and tail -f my_worker.log—verify only the two my_worker processes terminate and the script exits 0. Re-run immediately when zero workers exist—verify exit code 0 and zero kill errors. Launch a stubborn my_worker that ignores SIGTERM (trap '' TERM) with GRACE_SECONDS=2—verify it survives ~2 seconds and is then cleaned up by SIGKILL.
    • Command 2 checks: Test DEPLOY_DIR="/tmp/release v2 dir" (spaces in path) containing conf/.env (0666) and bin/migrate (0755) that writes one stdout line, one stderr line, and exits 3—verify .env becomes 0640 (rw-r-----), bin/migrate stays 0750 (rwxr-x---), both output lines appear in migrate-*.log, migrate.pid records the integer PID, and the script exits 3. Finally, test a read-only file where chmod fails—verify bin/migrate never executes at all.

Intuition & how it works

Think of managing servers with fragile shell one-liners like shouting instructions across a noisy warehouse. Command 1 (ps aux | grep my_worker | ... | xargs kill -9) tells security to "immediately eject anyone whose badge or clipboard mentions my_worker"—which sweeps up the health watchdog (my_worker_watchdog.py), someone reading the shift log (tail -f my_worker.log), and even the security guard holding the note (grep my_worker), without giving the actual worker five seconds to put down heavy machinery! Command 2 (chmod -R 777 $DEPLOY_DIR && ./bin/migrate ... 2>&1 > /dev/null &) unlocks every door in the building to strangers (777), miswires the intercom (2>&1 > /dev/null), and walks away (&) before checking whether the doors were even unlocked.

Naive fixes fall short because shell pipelines and expansions fail silently on boundaries. Adding grep -v grep still kills my_worker_watchdog.py and still fails on GNU xargs when zero workers exist; fixing > /dev/null 2>&1 still throws away migration errors; and leaving chmod inside ... && ... & runs the permission update asynchronously in a background subshell where failures go unnoticed.

Walk through two concrete mini-traces to see why exact process matching, quoting, foreground ordering, and left-to-right file descriptor (integer stream handle: 1 for stdout, 2 for stderr) binding matter: - Command 1 on 3 processes: Suppose PID 501 is my_worker, PID 502 is my_worker_watchdog, and PID 503 is grep my_worker. The original pipeline runs kill -9 501 502 503 (killing the watchdog and failing with exit 123 because 503 already exited). Our hardened script runs pgrep -u "$owner" -x my_worker, gets [501] only, sends SIGTERM (-15), polls up to 30s, and escalates to SIGKILL (-9) only if 501 is still running as my_worker. - Command 2 on DEPLOY_DIR="/srv/release v2": Unquoted $DEPLOY_DIR splits into /srv/release and v2, and 2>&1 > /dev/null points fd 2 at the old terminal before pointing fd 1 at /dev/null (throwing away stdout while leaking stderr). Our hardened script validates DEPLOY_DIR and ENV, runs chmod -R -- u=rwX,g=rX,o= . in the foreground so any failure stops immediately, then runs ./bin/migrate --env="$ENV" >>"$log_file" 2>&1 &, records migrate_pid=$!, and waits for its exit code.

Key points

  • Match kernel process metadata, never ps text output: Use pgrep -u "$owner" -x my_worker (exact process name, scoped to one user, never self-matching) or pgrep -fx for anchored command lines—or better yet, stop services via their supervisor/systemd cgroup (a Linux kernel group tracking a service and all its child processes).
  • Graceful SIGTERM before forceful SIGKILL: SIGTERM (signal 15) lets workers checkpoint state, release locks, and close sockets cleanly; SIGKILL (signal 9) cannot be caught and should only fire after a bounded grace timeout, re-verifying PID identity right before escalating to shrink TOCTOU (time-of-check to time-of-use race) risk.
  • Zero matches must succeed cleanly: GNU xargs runs its command once even on empty input unless -r is passed; checking (( ${#pids[@]} == 0 )) explicitly turns "already stopped" into a clean exit 0.
  • Shell operator precedence (&& beats &): A && B & runs { A && B; } & entirely in the background. Run prerequisite steps like chmod in the foreground under set -euo pipefail so failures block migrate from starting.
  • Left-to-right redirection binding: Write >>"$log_file" 2>&1 (point fd 1 at the file first, then copy fd 1's new target into fd 2), never 2>&1 >>"$log_file".
  • Quoting, validation, and least privilege: Quote every "$VAR" to prevent word splitting (breaking on whitespace) and glob expansion (expanding */?), validate non-empty inputs with ${VAR:?}, end option flags with --, and replace 777 with chmod -R -- u=rwX,g=rX,o= plus umask 027.

Common mistakes

  • Patching grep with grep -v grep or grep '[m]y_worker': That avoids matching grep itself, but still kills my_worker_watchdog.py, tail -f my_worker.log, and any parent bash -c wrapper whose arguments mention my_worker.
  • Replacing the pipeline with pkill -f my_worker: Without -x, -f still does an unanchored substring regex match across every command line, repeating the exact same collateral damage!
  • Replacing chmod -R 777 with chmod -R 755: 755 (rwxr-xr-x) still leaves .env secrets world-readable to every local user and adds execute bits to plain data/config files; symbolic u=rwX,g=rX,o= uses capital X to keep ordinary files non-executable and private.
  • Assuming set -u catches DEPLOY_DIR="": set -u (nounset) errors only on unset variables, whereas ${DEPLOY_DIR:?} rejects both unset and empty-string values.
  • Polling only kill -0 "$pid" during a 30-second grace loop: kill -0 only asks "does some process own this PID?"—if the worker exited and the OS recycled the PID to a new process during the wait, kill -KILL "$pid" would kill an innocent bystander unless you re-check the process name/start time.
  • Reading $! after running another command: $! holds only the most recent background job's PID, so capture migrate_pid=$! on the very next line after &.

Follow-up questions

  • What distinguishes pkill -x from pkill -f, and how can OS PID reuse still cause a race between finding a process and signaling it? By default, pkill matches a regular expression anywhere inside the kernel's short process name (comm, truncated to 15 characters on Linux): pkill -x pattern requires the pattern to match that entire process name from start to finish, whereas pkill -f pattern searches the entire full command line (argv, including script paths and flags)—and combining -fx anchors the match to the whole command line. PID reuse bites whenever a target process exits after discovery and high process churn wraps the kernel's PID counter (/proc/sys/kernel/pid_max) back around to that same integer before kill(2) runs—a tiny microsecond window inside a single pkill, but a huge 30-second window between SIGTERM and SIGKILL in a shutdown script! You eliminate or shrink this race by signaling direct child processes (whose PIDs cannot be recycled until the parent waits/reaps them), opening a Linux pidfd (pidfd_open, a file descriptor bound permanently to one specific process incarnation rather than a reusable integer), or re-checking /proc/<pid>/stat start time (starttime) and process name right before sending SIGKILL.
  • What happens when chmod -R 777 $DEPLOY_DIR runs in a shell without set -u while DEPLOY_DIR is unset or blank? Because $DEPLOY_DIR is unquoted, an unset or empty variable expands to zero words (it vanishes completely after word splitting), turning the command into chmod -R 777 with no path operand. GNU chmod prints chmod: missing operand after '777' and exits 1, which causes && to skip ./bin/migrate—and because & ran the whole chain in the background without wait, the failure is completely silent! Worse yet, tiny variations turn catastrophic: chmod -R 777 $DEPLOY_DIR/ expands to chmod -R 777 /, and unlike rm, GNU chmod does not enable --preserve-root by default, so running as root would recursively 777 the entire root filesystem; always guard paths with : "${DEPLOY_DIR:?}" and --preserve-root.
  • In a container or CI job, how can a shell script guarantee that its background child process terminates cleanly whenever the shell itself gets SIGTERM? Install a trap in the parent shell for TERM (and INT/EXIT) that forwards SIGTERM to the child's saved $child_pid and waits for the child to exit cleanly, and block the parent using bash's wait "$child_pid" builtin rather than foreground execution (bash defers traps while a foreground external command runs, whereas a trapped signal interrupts wait immediately!). Inside a container, also watch out for PID 1 semantics: Linux ignores unhandled SIGTERM sent to PID 1, and if your shell exits early without reaping children, orphans hang or get abruptly SIGKILLed when the container stops—so run a lightweight init (docker run --init / tini -g to forward signals to the whole process group) alongside a trap handler like trap 'kill -TERM "$child_pid" 2>/dev/null || true; wait "$child_pid" 2>/dev/null || true; exit 143' TERM.

Follow-up questions

Similar questions

More Modal interview questions

All 3 Modal questions →