Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a bash script when the python script that is called within bash encounters an error?

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.

like image 394
wiswit Avatar asked Feb 09 '23 19:02

wiswit


1 Answers

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
like image 133
chepner Avatar answered Feb 12 '23 09:02

chepner