0

I have done some research on pipe and subshell

Each command in a multi-command pipeline, where pipes are created, is executed in its own subshell, which is a separate process (see Command Execution Environment). If the lastpipe option is enabled using the shopt builtin (see The Shopt Builtin), the last element of a pipeline may be run by the shell process when job control is not active.

test code

#!/bin/bash


set +m

shopt -u lastpipe
shopt | grep lastpipe

function test() {
  echo "This is first pipe"  | echo $BASH_SUBSHELL
}

test

shopt -s lastpipe
shopt | grep lastpipe

function test() {
  echo "This is first pipe"  | echo $BASH_SUBSHELL
}

test

Output is

lastpipe        off
0
lastpipe        on
0

Expected result is

lastpipe        off
1
lastpipe        on
0

1 Answer 1

3

Your problem is that variable substitution is performed before the pipeline runs. When you write:

echo "This is first pipe"  | echo $BASH_SUBSHELL

The $BASH_SUBSHELL is expanded in the current shell before it runs the pipeline. To properly perform your test, you would need to place your echo statement in a function to defer substitution:

test_subshell() {
  echo $BASH_SUBSHELL
}

Then you will see different behavior:

$ test_subshell
0
$ echo "This is first pipe" | test_subshell
1
6
  • I disagree. BASH_SUBSHELL is expanded in the child shell.
    – KamilCuk
    Aug 7, 2023 at 10:59
  • I am happy to entertain the idea that my answer is incorrect, but rather than just telling us it's wrong can you provide an updated answer? Why does echo foo | echo $BASH_SUBSHELL show a different value than echo foo | test_subshell?
    – larsks
    Aug 7, 2023 at 11:52
  • yes, so I can't answer, so I guess until I can prove otherwise, you can ignore me. Does export BASH_SUBSHELL; echo | env | grep BASH_SUBSHELL prove it? Or echo | { echo $BASH_SUBSHELL; }? I tried reading docs, and I do not think it is 100% clear when after tokenization the expansions happen.
    – KamilCuk
    Aug 7, 2023 at 11:59
  • 1
    I always thought that variable substitution of the entire pipeline happens before the pipeline is executed...e.g., the bash man page says, "Expansion is performed on the command line after it has been split into words.", and I took that to mean, "before executing anything".
    – larsks
    Aug 7, 2023 at 12:29
  • For example echo $BASHPID; echo | echo $BASHPID returns two different pids.
    – KamilCuk
    Aug 7, 2023 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.