Skip to content

Instantly share code, notes, and snippets.

@jesugmz
Last active February 24, 2019 22:46
Show Gist options
  • Save jesugmz/3fda0fc7c1006cedfe039ff1459c3174 to your computer and use it in GitHub Desktop.
Save jesugmz/3fda0fc7c1006cedfe039ff1459c3174 to your computer and use it in GitHub Desktop.
Check if there is shell command output

Check if there is shell command output

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.

Simple solution

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'
fi

Low memory consumption solution

If 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'
fi

Instead of an echo, an exit code can be returned to control flows:

output=$(radon cc . -nc)

if [[ -n "$output" ]]; then
  exit 1
fi

Showing original output solution - keeping colors and format

The execution of the scripts above will produce an exit code 1 if there is output:

$ bash test.sh; echo $?
1

but, 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
fi

script 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment