error linux

Linux Exit Code 1 - General Error

Understanding Linux exit code 1 - a general catchall error indicating the command failed for an unspecified reason.

What It Means

Exit code 1 is the most common non-zero exit code and is used as a general catchall for miscellaneous errors. It indicates that the command or program failed, but the specific error doesn’t have its own dedicated exit code.

Many programs use exit code 1 for any generic failure, making it the most frequently encountered error code.

Common Causes

  • General command failure (e.g., grep finding no matches)
  • Script encountering a runtime error
  • Failed assertions or validation checks
  • File operations that fail (cannot read, write, or create)
  • Program-specific error conditions
  • Test failures
  • Build failures
  • Configuration errors

How to Fix

Identify the actual error

# Check the error output of the command
your_command 2>&1 | tail -20

# Run with verbose output if supported
your_command --verbose
your_command -v

# Check stderr separately
your_command 2>/tmp/error.log
cat /tmp/error.log

Common scenarios and fixes

# grep returns 1 when no match is found — this may not be an error
grep "pattern" file.txt
echo $?  # 1 if no match, 0 if found

# In scripts, handle grep's exit code explicitly
if grep -q "pattern" file.txt; then
  echo "Found"
else
  echo "Not found — this might be expected"
fi

# diff returns 1 when files differ — not necessarily an error
diff file1.txt file2.txt
echo $?  # 1 if different, 0 if identical

Error handling in bash scripts

#!/bin/bash
set -e  # Exit immediately if a command exits with non-zero

# Or handle errors explicitly
if ! npm install; then
  echo "Failed to install dependencies"
  exit 1
fi

if ! npm test; then
  echo "Tests failed"
  exit 1
fi

echo "All steps completed successfully"
exit 0

Using trap for cleanup on error

#!/bin/bash

cleanup() {
  echo "Cleaning up..."
  rm -f /tmp/tempfile
}

trap cleanup EXIT  # Run cleanup on any exit (0 or non-zero)

# Your script logic
process_data || exit 1

Debugging exit code 1 in CI/CD

# GitHub Actions - add debugging
steps:
  - name: Run build
    run: |
      set -ex  # Print commands and exit on error
      npm ci
      npm run build