KatInterview

Debug and Secure Shell Command Patterns

BehavioralModel answer
MediumModel answerBehavioralunixshelldebugging

Last updated

Diagnose failure modes in two Unix shell patterns and rewrite them with proper error handling, security practices, and stream management.

You're reviewing automation scripts and find two problematic shell commands that regularly cause issues in your deployment pipeline:

Command 1:

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

Command 2:

chmod -R 777 $TARGET_PATH && ./scripts/db_sync --mode=$MODE 2>&1 > /dev/null &

Both have caused production incidents: processes killed unexpectedly, permission vulnerabilities, and silent failures.

Your Task

For each command:

  1. Explain the execution flow: Walk through what happens at each step when the shell processes this command.

  2. Identify problems: Find at least three distinct issues. Consider:

    • Pattern matching behavior and false positives
    • Variable expansion and quoting
    • Permission security implications
    • Stream redirection semantics
    • Error visibility and exit code handling
    • Race conditions
  3. Write a hardened version that:

    • For Command 1: Matches only intended processes, handles zero matches gracefully, allows graceful shutdown before forcing termination
    • For Command 2: Uses minimal necessary permissions, handles special characters safely, logs output properly, and prevents the background job from running if setup fails

Include explanations of why your improvements address the original problems.

Hints

Hint 1

The grep process itself appears in ps output while the pipeline runs

Hint 2

Redirection operators are evaluated left-to-right, and 2>&1 captures the current destination of stdout

Hint 3

The & operator backgrounds the entire command sequence, not just the last part