Say I have a file myfile
in my current working directory. I want to set a variable if a command executes normally, but also use its result.
$ ls
You can use BASH_SUBSHELL variable to verify whether you're in subshell or not.
# BASH_SUBSHELL will print level of subshell from top due to pipe
{ unset v && ls file && v=3 && echo "$BASH_SUBSHELL - $v"; } | nl
1 file
2 1 - 3
# outside BASH_SUBSHELL will print 0
echo "$BASH_SUBSHELL - $v";
0 -
You can use for piped command it prints 1
meaning it is in a subshell hence value of v
isn't available outside (evident from 2nd output)
It's not the curly braces that are causing a subshell to be created, it's the pipe.
To prove it:
$ { ls && v=3; } > tmp
$ echo "$v"
3
To quote Greg:
In most shells, each command of a pipeline is executed in a separate SubShell.