DevOps
Shell Scripting
Processes & Exit Codes

Processes & Exit Codes

DevOps automation often involves long-running tasks and checking if a command actually succeeded before moving to the next step.

1. Process Management

Background Execution

Adding an & at the end of a command runs it in the background, freeing up your terminal.

# Run a backup in the background
./backup.sh &

Managing Background Jobs

  • jobs: List current background processes.
  • fg: Bring a background job to the foreground.
  • bg: Resume a suspended job in the background.
  • nohup: Run a script that continues even if you log out.

2. Exit Status Codes

Every command returns an Exit Status (an integer between 0 and 255) to the system upon completion.

  • 0: Success.
  • 1-255: Failure (different codes indicate different types of errors).

Checking the Last Exit Code: $?

You can see the status of the immediate previous command using the $? variable.

ls /non-existent-path
echo $? # Output will be non-zero (e.g., 2)

3. Logical Operators

You can use exit codes to chain commands conditionally without an if statement.

&& (AND): Run second command only if the first succeeds.

mkdir backup_dir && cd backup_dir

|| (OR): Run second command only if the first fails.

ping -c 1 internal.server || echo "Server is down!"

Practical Example: Process Watcher

A script that checks if a process is running and logs its status.

#!/bin/bash
 
PROCESS="nginx"
 
if pgrep "$PROCESS" > /dev/null; then
    echo "$(date): $PROCESS is running." >> status.log
    exit 0
else
    echo "$(date): WARNING: $PROCESS is down!" >> status.log
    exit 1
fi

[!TIP] Exit Early In automation scripts, use set -e at the top. This tells the script to exit immediately if any command fails, preventing a chain reaction of errors.