Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash 4.3 lastpipe bug or feature?

Tags:

bash

pipeline

I try to use the lastpipe option in the bash and it seems to not work as expected when run from the interactive prompt command line.

phi@phiz:~$ shopt lastpipe
lastpipe        on

phi@phiz:~$ echo $BASH_VERSION
4.3.11(1)-release

phi@phiz:~$ echo yo | read a ; echo "a='$a'"
a=''

So I don't get anything in $a, yet if run in a sub process it kinda works though useless I need it in the top level interactive

phi@phiz:~$ (echo yo | read a ; echo "a='$a'")
a='yo'

Is this behavior expected? I did my RTFM duties and could not decide if this was intended or unexpected.

I am new to bash and this confusing when coming from other shells

Thanks in advance for any advices.

like image 639
Phi Avatar asked Nov 08 '25 21:11

Phi


1 Answers

Quoting from the documentation:

'lastpipe'
     If set, and job control is not active, the shell runs the last
     command of a pipeline not executed in the background in the
     current shell environment.

In a normal interactive shell, job control is active, so the lastpipe option has no effect. In a subshell, job control is not active, so the lastpipe option does take effect.

Job control refers to things like the ability to suspend jobs with ^Z and then resuming them with fg, so this is something you generally want. In your case, I might try to re-write instead to

a=$(echo yo); echo "a='$a'"

or if you really need only the first line of some other command, pipe it through head -n1.

If, on the other hand, you do decide that you don't need job control, you can disable it with set +m (as pointed out by @chepner), and optionally later re-enable it with set -m.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!