For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/bash-code-quality/avoid-indirect-exit-code-check.md. A documentation index is available at /llms.txt.

Test commands directly instead of reading $? in a bracket test

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

Metadata

ID: bash-code-quality/avoid-indirect-exit-code-check

Language: Bash

Severity: Notice

Category: Code Style

Description

Writing a command and then testing $? in a separate [/[[/test condition is redundant and brittle: another command between them changes $?, set -e can exit before the check, and [/[[ themselves overwrite $? before the branch body runs. It is better to use if cmd; then, if ! cmd; then, or capturing the output with if ! out=$(cmd); then instead of inspecting $? in the conditional.

Non-Compliant Code Examples

#!/bin/bash
make all;
if [ $? -eq 0 ]; then :; fi
if [[ $? -ne 0 ]]; then :; fi
if [ "${?}" -eq 0 ]; then :; fi
test $? -eq 0 && echo bad
/usr/bin/test $? -eq 0

Compliant Code Examples

#!/bin/bash
if grep -q pat file; then echo ok; fi
if ! make all; then echo fail; fi
if [ -f "$f" ]; then :; fi
rc=$?
if [ "$rc" -eq 0 ]; then :; fi
echo "status was $?"
if test -n "$file"; then :; fi
/usr/bin/test -f "$path" && echo ok
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