Reputation: 996
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 :)
Upvotes: 3
Views: 651
Reputation: 2682
The solution is $!
. As in:
#!/bin/bash
echo "parent" $$
yes > /dev/null &
echo "child" $!
Output:
$ ./prueba.sh
parent 30207
child 30209
Upvotes: -1
Reputation: 3037
echo "one.sh $$"
echo `eval echo '$$'`
I am expecting the above to print different pids, but it doesn't. It's creating a child process. Verified by adding sleep in ``.
echo "one.sh $$"
echo `eval "echo '$$'";sleep 10`
On executing the above from a script and running ps shows two processs one.sh(name of the script) 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 output produced
one.sh 12685
12685
Not sure what i am missing.
Upvotes: 0
Reputation: 881403
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 $$'
Upvotes: 6