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:
- Why just three echo prints? There are 4 echos in my code.
- Why three pids are the same? subshell’s pid is obviously not same with his father’s.
Thanks a lot for answers 🙂
First, the assignment captures standard output of the child and puts it into
var, rather than printing it:This can be seen with:
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 executingecho 9098rather thanecho $$.If you want the PID of the child, you have to prevent translation in the parent, such as by using single quotes: