0
if ! output=$(some_command);
then
    printf "Error occurred, error output is =\n%s", "$output"

Could you please suggest if this is a good way to do it? I am testing - If the exit status of the command is 1, then only I want to print the contents of the output. If the exit status of the command is 0, then do nothing. Don't print output.

ugola
  • 300
  • 3
  • 18
  • Try `output="$(some_command)"; if [[ -n $output ]]; then printf "output is =\n%s" "$output"; fi` – anubhava Sep 26 '22 at 19:39
  • The construct in your condition (with `!`) is testing the _exit status_ of the command, not the contents of the variable. It is very useful in that aspect, just not as the text of your question describes. – glenn jackman Sep 26 '22 at 19:46
  • Thanks Glenn. I have updated as per your comment. – ugola Sep 26 '22 at 20:37

3 Answers3

2

This doesn't allow you to print data before the output of the command, but after:

if some_command | grep .; then
    echo "the output was as above"
fi

If you really want to print text before, you can store it and do:

if output=$(some_command | grep .); then
    printf "the output is:%s\n" "$output"
fi

Or you can be more explicit and do:

output=$(some_command)
if test -n "$output"; then
    printf "the output is:%s\n" "$output"
fi
William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

You're testing whether the command was successful, not whether it returned output.

Assign the variable separately from the if statement.

output=$(some_command)
if [ -n "$output" ]
then
    printf "output is =\n%s", "$output"
fi
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Do you want to print when there is no output? I read this as if not output print the following

If you want to print when it output is not null the following should work...

More info here: Check if string is neither empty nor space in shell script

temp=$(command)
if [[ -n "${temp// /}" ]];; then
        echo "output is $temp"
fi
parker
  • 11
  • 2