5

I have a very simple question as described in the title. I searched a bit online and find the answers are not easy to for me to catch. A minimum example is, I have a python script python_script.py:

#!/us/bin/python                                                           

import sys                                                                  

number = int(sys.argv[1])                                                        

if number <= 10:                                                            
    pass                                                                    
else:                                                                       
    raise ValueError('Number is higher than 10!')                           
    sys.exit(1)                                                                                     

Then I have a bash script bash_script.sh which calls above python script.

#!/bin/bash                                                                 

for num in {1..100}                                                         
do                                                                          
  python python_script.py ${num}                                            
done          

What I tried to do is: After the exception is raised in python script, I want to the bash script to stop immediately (i.e., when num>10 in this example). But now with these two scripts, all num loops from 1 to 100 are executed in bash script, but only after 10 the exception is printed on screen. I guess this should be quite easy so thank you in advance for the help.

1 Answer 1

9

You can test the exit status of the python script and exit the bash script if it is non-zero. The simplest way is

#!/bin/bash                                                                 

for num in {1..100}                                                         
do                                                                          
  python python_script.py ${num} || exit                                         
done    

but you can also use an if statement:

for num in {1..100}
do
    if ! python python_script.py ${num}; then
        echo "An error occurred"
        exit
    fi
done
Sign up to request clarification or add additional context in comments.

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.