bash exit codes - ghdrako/doc_snipets GitHub Wiki

Strategies for Discovering Exit Codes

Here’s how to find the return code meanings for the commands you frequently use:

  1. Manual Pages (man) Search man pages (e.g., man grep, man diff) for sections titled “Exit Status” or “Diagnostics.”
  2. Command Documentation: Often, online wikis or command-specific documentation websites list and explain exit codes.
  3. Experimentation: Purposely induce errors (bad file names,etc.) and examine the exit status using echo $?

Caution with Assumptions

  • Not all commands provide detailed exit codes. It’s essential to consult reliable documentation sources to avoid surprises.
  • Exit code meanings can sometimes slightly differ between implementations of the same command (e.g., GNU vs BSD-like systems). Test on your target systems.
#!/bin/bash
backup_file="/path/to/important_data.txt"
backup_destination="/backup/location"
cp $backup_file $backup_destination # Attempt backup
if [ $? -eq 0 ]; then
  echo "Backup successful!"
else
  echo "Backup failed. Check permissions or disk space."
  # Optionally add logic to send an email or alert
fi

Dependency checking

#!/bin/bash
command -v unzip >/dev/null 2>&1 # Check if 'unzip' is installed
if [ $? -ne 0 ]; then
  echo "'unzip' is required. Please install."
  exit 1
fi

Network Troubleshooting

#!/bin/bash
ping -c 2 www.google.com
if [ $? -ne 0 ]; then
  echo "Internet connection appears offline. Check your network."
else
  echo "Connected to the internet."
fi

Retry logic

#!/bin/bash
attempts=0
max_attempts=3
while [ $attempts -lt $max_attempts ]; do
  rsync -avz remote_folder/ ./local_backup/
  if [ $? -eq 0 ]; then
    echo "Backup successful after $attempts tries"
    break # Exit loop on success
  fi
  let attempts=attempts+1
  echo "Backup failed. Retrying in 5 seconds..."
  sleep 5
done