Consider the following scenario:
Problem The execution of a shell command (Radon in this example) does not retrieve an status code different to 0 when there is output (if there is output there are issues). The command does not gives parameter to handle it.
Check if the length of the output is non empty (-n).
output=$(radon cc . -nc)
if [[ -n "$output" ]]; then
echo 'there is output'
else
echo 'no output'
fiIf the output of the command is huge consider just store a flag as follow:
Extract the first byte (head -c1) of the string output and count it (wc -c) without storing its output.
output=$(radon cc . -nc | tr -d ' \n\r\t ' | head -c1 | wc -c)
if [[ $output -ne 0 ]]; then
echo 'there is output'
else
echo 'no output'
fiInstead of an echo, an exit code can be returned to control flows:
output=$(radon cc . -nc)
if [[ -n "$output" ]]; then
exit 1
fiThe execution of the scripts above will produce an exit code 1 if there is output:
$ bash test.sh; echo $?
1but, if we want to show also the original output keeping its format? it means color and other text formats:
output=$(script --quiet --flush --command 'radon cc . -nc' /dev/null | sed '1d')
if [[ -n "$output" ]]; then
echo -e "${output}"
exit 1
fiscript will record as first line the timestamp of the execution so is needed to remove this first line (sed '1d').
Credits for the huge resources consumption solution to https://stackoverflow.com/a/35165216/4411354.