About shell and subshell

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 :)

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 $$'

Need Your Help

How does a very small number behave while processing?

java types processing primitive-types

Well I am working on a big dataset and after some calculations I am getting values for the features like 4.4E-5. I read it somewhere those values means 0.000044 that is ten to the power minus 5. So...

Starting service from intent in another service gets a run time error

java android

I'm getting an error when trying to start a service with an intent from another service in an Android 2.3.3 project. The error is: Unable to start service with Intent{ act=(class name) cmp=(class n...