Here's a preview from my zine, Bite Size Bash! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!
get the zine!
read the transcript!
a subshell is a child shell process
bash, represented by a box with a smiley face: hey, can you run this bash code for me?
other bash process: sure thing!
some ways to create a subshell
-
put code in parentheses
(...)
(cd $DIR; ls)
(runs in subshell) -
put code in
$(...)
var=$(cat file.txt)
(runs in subshell) -
pipe/redirect to a code block
cat x.txt while read line...
(piping to a loop makes the loop run in a subshell) -
and lots more
for example, process substitution<()creates a subshell
cd in a subshell doesn’t cd in the parent shell
(
cd subdir/
mv x.txt y.txt
)
I like to do this so I don’t have to remember to cd back at the end!
setting a variable in a subshell doesn’t update it in the main shell
var=3
(var=2)
echo $var
(this prints 3, not 2)
it’s easy to create a subshell and not notice
x=$(some_function)
sad stick person: I changed directories in some_function, why I didn’t it work?
happy stick person: it’s running in a subshell!