4

The following code works differently depending on which way Parse_Short_Switches() is called. After calling the function 'Parse_Short_Switches' by using result=$(Parse_Short_Switches), the value of $error_flag is NOT set to -1 as I would expect.

After calling the function 'Parse_Short_Switches' by simply using Parse_Short_Switches, the the value of $error_flag is set to -1 as I would expect.

Any help would be greatly appreciated. Thanks

#!/bin/bash

function Parse_Short_Switches()
{
echo "error_flag inside of the function= $error_flag" 1>&2
error_flag="-1"
echo "blah blah ..."
}

# --- MAIN ---
error_flag="999"
echo "error_flag= $error_flag"
#result=$(Parse_Short_Switches)
Parse_Short_Switches
echo "error_flag= $error_flag"
BASH
  • 61

1 Answers1

5

That's because the command substitution, $(), spawns a subshell and the command inside runs in that subshell.

So any modifications made to any data structure would not be propagated to the parent shell. In other words, the changes are being made all right but in a subshell, hence the parent shell's relevant parameters are not being affected.

As a side note, when you execute a script, it runs in a subshell; A common trick to make all the changes of the parameters to be available in the calling shell is to source (.) the script.

Example:

$ foo() { bar=2 ;}

$ bar=1

$ $(foo)

$ echo "$bar"
1

$ foo

$ echo "$bar"
2
heemayl
  • 93,925