Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About shell and subshell

Tags:

linux

bash

shell

I'm new to shell,I just learned that use (command) will create a new subshell and exec the command, so I try to print the pid of father shell and subshell:

#!/bin/bash

echo $$
echo "`echo $$`"
sleep 4
var=$(echo $$;sleep 4)
echo $var

But the answer is:

$./test.sh
9098
9098
9098

My questions are:

  1. Why just three echo prints? There are 4 echos in my code.
  2. Why three pids are the same? subshell's pid is obviously not same with his father's.

Thanks a lot for answers :)

like image 461
Coaku Avatar asked Feb 28 '26 13:02

Coaku


1 Answers

First, the assignment captures standard output of the child and puts it into var, rather than printing it:

var=$(echo $$;sleep 4)

This can be seen with:

$ xyzzy=$(echo hello)
$ echo $xyzzy
hello

Secondly, all those $$ variables are evaluated in the current shell which means they're turned into the current PID before any children start. The children see the PID that has already been generated. In other words, the children are executing echo 9098 rather than echo $$.

If you want the PID of the child, you have to prevent translation in the parent, such as by using single quotes:

bash -c 'echo $$'
like image 174
paxdiablo Avatar answered Mar 03 '26 04:03

paxdiablo



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!