Home > Mobile >  Bash check if command returns output, and print it
Bash check if command returns output, and print it

Time:09-27

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related