SC2164: cd Without Error Handling in Shell Scripts

Handle cd failures properly to prevent scripts from operating in the wrong directory. Use cd dir || exit 1 or set -e for safety.

Error Handling

Detailed Explanation

Why cd Failures Are Dangerous

When cd fails (directory does not exist, no permission), the script continues in the current directory. Subsequent commands then operate on the wrong files, potentially causing data loss.

The Problem

cd /app/deploy
rm -rf old_files/
# If /app/deploy doesn't exist, rm runs in the PREVIOUS directory!

Solution 1: cd ... || exit

cd /app/deploy || { echo "Failed to cd to /app/deploy" >&2; exit 1; }
rm -rf old_files/

Solution 2: set -e

set -e
cd /app/deploy  # Script exits automatically on failure
rm -rf old_files/

Solution 3: Subshell

Use a subshell to scope the directory change:

(
  cd /app/deploy || exit 1
  rm -rf old_files/
)
# Back in original directory, even if cd succeeded

Solution 4: pushd/popd

pushd /app/deploy > /dev/null || { echo "Failed to cd" >&2; exit 1; }
rm -rf old_files/
popd > /dev/null

Common Pattern: Build Scripts

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR" || exit 1

# Now we know we're in the script's directory
source ./config.sh
./build.sh

The CDPATH Gotcha

If CDPATH is set, cd might go to an unexpected directory:

export CDPATH="/home/user"
cd projects  # Might go to /home/user/projects, not ./projects!

# Fix: use explicit path
cd ./projects  # Always relative to current directory

Use Case

Build scripts, deployment automation, cron jobs, and any script that changes directories before performing file operations. Essential for scripts that run as root or with elevated privileges.

Try It — Shell Script Linter

Open full tool