I have a python script that constantly exits exit code 42. Question: how can I replace the exit code in bash with another one, while keeping the number for further processing?

#!/bin/bash -xe my_script.py 
  • one
    1. What exactly is the meaning of the word β€œreplace”? 2. What is the line you brought in the question? - aleksandr barakin
  • @alexanderbarakin This is a line from my bash script, the -xe flags imply that the script will immediately stop if there is a nonzero exit code, my_script.py returns 42, so the script immediately drops. I want to be able to replace the return code 42 by 0 in the bash script so that the script does not fall. - nick_gabpe

2 answers 2

once you use the -e option of the bash program, the command inside the script that returns a non-zero return code will stop further interpretation of your script. to ignore a nonzero return code, you can, for example, use the list operator || :

 ΠΊΠΎΠΌΠ°Π½Π΄Π°-которая-ΠΌΠΎΠΆΠ΅Ρ‚-Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ-ΠΎΡˆΠΈΠ±ΠΊΡƒ || ΠΊΠΎΠΌΠ°Π½Π΄Π°-которая-выполнится-Π²-этом-случаС 

if the ΠΊΠΎΠΌΠ°Π½Π΄Π°-которая-ΠΌΠΎΠΆΠ΅Ρ‚-Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ-ΠΎΡˆΠΈΠ±ΠΊΡƒ returns a non-zero return code, then the ΠΊΠΎΠΌΠ°Π½Π΄Π°-которая-выполнится-Π²-этом-случаС will be executed, and if this second command returns the zero return code, the script will continue to be interpreted in "normal mode".

The simplest example for the second command is this : (colon, see $ help : for details). it does nothing, and ends with a zero return code.

such a construction will not lead to the termination of interpretation when using the -e option, even if the first command returns a non-zero return code:

 ΠΊΠΎΠΌΠ°Π½Π΄Π°-которая-ΠΌΠΎΠΆΠ΅Ρ‚-Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ-ΠΎΡˆΠΈΠ±ΠΊΡƒ || : 

since you need to save the return code of the β€œproblem” command, the most logical is on the right side of the operator || perform the assignment of the return code of the last command executed (stored in the $? variable) to some variable (for example, $result ):

 ΠΊΠΎΠΌΠ°Π½Π΄Π°-которая-ΠΌΠΎΠΆΠ΅Ρ‚-Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ-ΠΎΡˆΠΈΠ±ΠΊΡƒ || result=$? 

assignment operator result=$? always successful, because the interpretation of the script will not be interrupted.


total:

 #!/bin/bash set -e result=0 my_script.py || result=$? echo "ΠΊΠΎΠ΄ Π²ΠΎΠ·Π²Ρ€Π°Ρ‚Π° ΠΏΡ€ΠΎΠ±Π»Π΅ΠΌΠ½ΠΎΠΉ ΠΊΠΎΠΌΠ°Π½Π΄Ρ‹: $result" 

    In the piggy bank.

    In bash, there is already an internal array variable, which is like the status of a conveyor or a single executed command:

     PIPESTATUS 

    measure:

     ~$ ls -la | grep emacs drwx------ 3 u0_a207 u0_a207 4096 Sep 4 19:58 .emacs.d ~$ echo ${PIPESTATUS[@]} 0 0 

    Links

    • PIPESTATUS may be useful, but it is not clear how this answers the current question. If you find something interesting (β€œhow to get the status of teams in the pipeline to get in the bash”) and want to share with others (or the future yourself), you can ask and answer the question yourself - this is clearly welcomed - jfs