0
#!/bin/bash

function make_exit() {
    if [ "$1" = "exit" ]; then
        echo 'exit 1'
        exit 1 # I want the whole script to exit
    fi
}

echo -e "line1\nline2" | while read -r line; do
    echo "start while,${line}"
    make_exit "exit"
    echo "end while,${line}"
done

# Why is it implemented here
echo 'end script'

The result of executing the above script,But I want to exit the whole script at exit 1 of make_exit.

./test.sh 
start while,line1
exit 1
end script

But the following writing works correctly.

#!/bin/bash

function make_exit() {
    if [ "$1" = "exit" ]; then
        echo 'exit 1'
        exit 1 # I want the whole script to exit
    fi
}

echo -e "line1\nline2" > input

while read -r line; do
    echo "start while,${line}"
    make_exit "exit"
    echo "end while,${line}"
done <input

# Why is it implemented here
echo 'end script'
./test.sh 
start while,line1
exit 1

I probably guessed that the problem was caused by the pipeline, but the specific reason is not clear

janbar
  • 1
  • 1
  • 1
  • In the first case, the loop body runs as a child process (because it's on the receiving end of a pipeline), while in the second case, the loop body runs in the process of your shell script itself. – user1934428 May 26 '22 at 06:36
  • 3
    The pipeline makes the `while ... done` loop execute in a subshell, and `exit` only exits that subshell. See ["Bash subshell/pipelines - which parts are executing in subshells?"](https://stackoverflow.com/questions/9109362/bash-subshell-pipelines-which-parts-are-executing-in-subshells) and ["Exit bash script within while loop"](https://stackoverflow.com/questions/43483661/exit-bash-script-within-while-loop). – Gordon Davisson May 26 '22 at 06:39
  • @GordonDavisson Thank you very much, your answer is very helpful to me – janbar May 26 '22 at 06:59
  • @user1934428 Hmm, I probably understand something – janbar May 26 '22 at 07:00
  • This is also the topic of [BashFAQ #24](https://mywiki.wooledge.org/BashFAQ/024). BTW, don't use the `function` keyword -- see https://wiki.bash-hackers.org/scripting/obsolete; `function funcname() {` combines the POSIX-standard syntax `funcname() {` and the 1980s ksh syntax `function funcname {` in a way that's incompatible with *both* POSIX and ksh. – Charles Duffy May 26 '22 at 17:07
  • @CharlesDuffy I always thought that it would be more clear to bring the `function`, but I didn't expect there would be a problem, thank you – janbar May 27 '22 at 08:02

0 Answers0