Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

This question already has an answer here:

#!/bin/bash

function abc() # wait for some event to happen, can be terminated by other process
{
    sleep 3333 
}

echo "PID: $$"
abc &
echo "PID: $$"

I need to retrieve the pid of this function, but the echo prints the same string.

If I'm not going to put abc() out of this script, is it possible to get it's pid and terminate that function?

share|improve this question

marked as duplicate by PersianGulf, cuonglm, Anthon, terdon Jun 7 at 11:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
This question is very similar to How to get the pid of the last executed command in shell script?. The only essential difference is that this questions is asking about a function. But, as it turns out, it doesn't make the answer different (the function is executed in a backgrounded subshell). –  imz -- Ivan Zakharyaschev Jun 2 at 14:06

2 Answers 2

up vote 6 down vote accepted

You have two options, I think:

$BASHPID or $!

echo "version: $BASH_VERSION"
function abc() # wait for some event to happen, can be terminated by other process
{
          echo "inside a subshell $BASHPID" # This gives you the PID of the current instance of Bash.
          sleep 3333
}

echo "PID: $$" # (i)
abc &
echo "PID: $$" # (ii)
echo "another way $!" # This gives you the PID of the last job run in background
echo "same than (i) and (ii) $BASHPID" # This should print the same result than (i) and (ii)

sh-4.2$ ps ax|grep foo
25094 pts/13   S      0:02 vim foo.sh
25443 pts/13   S+     0:00 grep foo

sh-4.2$ ./foo.sh
version: 4.2.39(2)-release
PID: 25448
PID: 25448
another way 25449
same than (i) and (ii) 25448
inside a subshell 25449

sh-4.2$ ps ax|grep foo
25094 pts/13   S      0:02 vim foo.sh
25449 pts/13   S      0:00 /bin/bash ./foo.sh
25452 pts/13   S+     0:00 grep foo

Cheers,

Source: http://tldp.org/LDP/abs/html/internalvariables.html

share|improve this answer

I think you're looking for the $!

function abc() # wait for some event to happen, can be terminated by other process
{
    sleep 3333 
}

echo "PID: $$"
abc &
echo "PID: $!"
share|improve this answer
    
“!$”? Is that $! with a typo? –  manatwork Nov 26 '12 at 9:01
    
@manatwork yes. Fixed now. –  David Bain Nov 26 '12 at 9:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.