0

The topic proposed from the moderator does not answer this question.

The exit command in the following script is supposed to exit the entire script.
Which normally happens if you put an exit command into a function.
But not in this case:

#!/usr/bin/env bash


function embedded()
{
  exit 1
  ls | head -1
}

jo name="$(embedded)" \
   age=50

printf "\nThe script is still alive.\n"

Output:

{"name":null,"age":50}

The script is still alive.

It continues to execute the rest of the script.
Does someone know why this happens?
Is there something inside the jo program that prevents the exit?

theerrormagnet
  • 174
  • 2
  • 15
  • That's what a subshell _does,_ you can't make the parent shell exit, or otherwise modify its state, without its cooperation. A common arrangement would be `value=$(function) || exit; jo name="$value"` etc – tripleee Feb 08 '22 at 12:35
  • @That is not true. Usually an `exit` inside a functions exits the entire script. – theerrormagnet Feb 08 '22 at 12:39
  • 1
    You are missing the point. The command substitution `$(...)` creates a new shell instance; the function exits that alright, but the parent shell is unaffected. – tripleee Feb 08 '22 at 12:49
  • @tripleee Ok, I think that last comment was the missing piece of information I needed. That was the part I did not understand. Thanks. – theerrormagnet Feb 08 '22 at 13:20

0 Answers0