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?

3
  • 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? Commented Mar 1, 2022 at 8:37
  • Divide by zero? let x=1/0 Commented Mar 1, 2022 at 8: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. Commented Mar 2, 2022 at 0:26

1 Answer 1

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.

1
  • 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! Commented Mar 2, 2022 at 23:15

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.