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:
Thanks a lot for 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 $$'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With