0

Having read the docs and following this answer, I wanted to test it with a simple example:

test_1.sh

#!/usr/bin/bash

let x=1/0 echo $x

test_2.sh

#!/usr/bin/bash

printf "\nThis is 2\n"

But both of these implementations of control flow fail: run test_1, if unsuccessful, run test_2

# Just errors on line 1 of course
./test_1.sh 
if [ $? -ne 0 ]; then
    ./test_2.sh
fi

Also fails:

./test_1.sh || ./test_2.sh

Any tips for controlling flow between multiple scripts?

Wassadamo
  • 105
  • 1
    The exit status of the first script, which you use with || between the scripts, is the exit status of echo. Is that what you expect? – Kusalananda Mar 01 '22 at 08:37
  • Divide by zero? let x=1/0 – Romeo Ninov Mar 01 '22 at 08:37
  • I don't actually care about division by zero. I just have a process like test_1.sh that could result in success (return code 0), or failure (anything other than 0). I want something like test_2.sh to run only in the former case. – Wassadamo Mar 02 '22 at 00:26

1 Answers1

1

Based on your comment:

I just have a process like test_1.sh that could result in success (return code 0), or failure (anything other than 0). I want something like test_2.sh to run only in the former case.

you want the opposite of the snippets in your question.

./test_1.sh
if [ $? -ne 0 ]; then
    ./test_2.sh
fi

runs test_2.sh if test_1.sh indicates failure, as does

./test_1.sh || ./test_2.sh 

To run test_2.sh if test_1.sh indicates success, any of these will work:

./test_1.sh
if [ $? -eq 0 ]; then
    ./test_2.sh
fi
if ./test_1.sh; then
    ./test_2.sh
fi
./test_1.sh && ./test_2.sh

See What are the shell's control and redirection operators? for details.

Your current test_1.sh always indicates success, in spite of the division by zero. See Ignore or catch division by zero for details.

Stephen Kitt
  • 434,908
  • Thanks for clarifying my XY problem, fixing my faulty shell scripting (I don't enjoy sh, but use it when I have to), and sharing these resources! – Wassadamo Mar 02 '22 at 23:15