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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With