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 :;fiif[[$? -ne 0]];then :;fiif["${?}" -eq 0];then :;fitest$? -eq 0&&echo bad
/usr/bin/test $? -eq 0
Compliant Code Examples
#!/bin/bash
if grep -q pat file;thenecho ok;fiif ! make all;thenecho fail;fiif[ -f "$f"];then :;firc=$?if["$rc" -eq 0];then :;fiecho"status was $?"iftest -n "$file";then :;fi/usr/bin/test -f "$path"&&echo ok
シームレスな連携。 Datadog Code Security をお試しください
Datadog Code Security
このルールを試して、Datadog Code Security でコードを分析してみましょう
このルールの使用方法
1
2
rulesets:- bash-code-quality # Rules to enforce Bash code quality.