About shell and subshell
I'm new to shell, I just found out that the use (command) command will create a new subshell and execute the command, so I'm trying to print the pid of the father's shell and subshells:
#!/bin/bash
echo $$
echo "`echo $$`"
sleep 4
var=$(echo $$;sleep 4)
echo $var
But the answer is:
$./test.sh
9098
9098
9098
My questions:
- Why are there only three echo seals? There are 4 echoes in my code.
- Why are three pids the same? The subhell pid is obviously not the same as its father.
Thanks a lot for the answers :)
First, the assignment captures the standard output of the child and puts it in var
, rather than printing it:
var=$(echo $$;sleep 4)
This can be seen with
$ xyzzy=$(echo hello)
$ echo $xyzzy
hello
Second, all those variables $$
are evaluated in the current shell, which means they turn into the current PID before any children start. Children see a PID that has already been created. In other words, children are performing echo 9098
rather than echo $$
.
If you want the PID of the child, you need to prevent translation in the parent, for example by using single quotes:
bash -c 'echo $$'
echo "one.sh $$"
echo `eval echo '$$'`
I expect the above text to print different pids, but it doesn't. This creates a child process. Checked by adding sleep to `` .
echo "one.sh $$"
echo `eval "echo '$$'";sleep 10`
Executing the above from a script and running ps shows two processes one.sh (script name) and sleep.
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
test 12685 0.0 0.0 8720 1012 pts/15 S+ 13:50 0:00 \_ bash one.sh
test 12686 0.0 0.0 8720 604 pts/15 S+ 13:50 0:00 \_ bash one.sh
test 12687 0.0 0.0 3804 452 pts/15 S+ 13:50 0:00 \_ sleep 10
This is the result obtained
one.sh 12685
12685
Not sure what I'm missing.
Solution $!
. How in:
#!/bin/bash
echo "parent" $$
yes > /dev/null &
echo "child" $!
Output:
$ ./prueba.sh
parent 30207
child 30209