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.

3
  • Try output="$(some_command)"; if [[ -n $output ]]; then printf "output is =\n%s" "$output"; fi Commented Sep 26, 2022 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. Commented Sep 26, 2022 at 19:46
  • Thanks Glenn. I have updated as per your comment. Commented Sep 26, 2022 at 20:37

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.