---
title: Handle cd failures
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Handle cd failures
---

# Handle cd failures

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

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

**Language:** Bash

**Severity:** Warning

**Category:** Best Practices

## Description{% #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{% #non-compliant-code-examples %}

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

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

## Compliant Code Examples{% #compliant-code-examples %}

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

run_from_build() {
  cd build || return
  make install
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 