This product is not supported for your selected Datadog site. ().

Metadata

ID: bash-code-quality/handle-cd-failures

Language: Bash

Severity: Warning

Category: Best Practices

Description

Scripts that run commands after changing directory should ensure the directory change succeeded. A failed cd (wrong path, missing dir, permission denied, broken symlink) leaves later commands running in the previous directory, which can cause confusing or destructive behavior.

Require an explicit check: use cd /some/path || exit in the main script or cd /some/path || return inside a function.

Non-Compliant Code Examples

#!/bin/bash
cd /tmp/artifacts
rm -rf *.tmp

deploy() {
  cd /opt/myapp
  ./deploy.sh
}

Compliant Code Examples

#!/bin/bash
cd /var/log || exit
rm -rf *.*

run_from_build() {
  cd build || return
  make install
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security