2

I need to write a small shell script that will execute a python script and get the results.

When I try to run it this way it works:

#!/bin/sh
/usr/bin/python /etc/scripts/backup.py
result=$?

if [ $result -gt 0 ];
    then echo 'PROBLEM';
else
    echo 'OK';
fi

But if I try to do it this way, it fails:

#!/bin/sh
if [ $(/usr/bin/python /etc/scripts/backup.py) -gt 0 ];
    then echo 'PROBLEM';
else
    echo 'OK';
fi

It returns:

lab-1:/etc/scripts# ./audit_test_wrapper.sh
sh: 0: unknown operand
OK

And the results are wrong. It should be printing "PROBLEM"" instead of OK.

what I've tried so far

if [ $(/usr/bin/python /etc/scripts/backup.py) -ne 0 ];

returns

lab-1:/etc/scripts# ./audit_test_wrapper.sh
sh: 0: unknown operand
OK

And I also tried this:

if [ "$(/usr/bin/python /etc/scripts/backup.py)" -gt 0 ];

it returns:

lab-1:/etc/scripts# ./audit_test_wrapper.sh
sh: out of range
OK

Can someone point me in the right direction?

Thanks.

4

A command does not return its exit status ($?) on standard output. A command substitution ($(...)) captures the standard output.

Instead, just do

#!/bin/sh

if ! /usr/bin/python /etc/scripts/backup.py; then
   echo 'PROBLEM'
else
   echo 'OK'
fi

This would pick the first branch and print PROBLEM if the python script exited with a non-zero exit status.

You may read the if statement as "If the script did not succeed".

If you want to get rid of the !:

#!/bin/sh

if /usr/bin/python /etc/scripts/backup.py; then
   echo 'OK'
else
   echo 'PROBLEM'
fi

You may read the if statement as "If the script did succeed".


The error that you get comes from the fact that the script doesn't output anything, which means that the command substitution will be empty. Since it's unquoted, the command that the shell will try to execute will look like

if [ -gt 0 ]

This is a syntax error.

When quoting the command substitution, you essentially try to run

if [ "" -gt 0 ]

and the shell is not able to compare the empty string as an integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.