when I'm executing my bash-script, I'm getting the wrong PID. I'm needing the PID to kill the process at the end of it. This is a simplified script that is affected by the issue:

echo 'PASSWORD' | sudo -S ping -f '' & 
echo $PING_PID;

The output is for example

[1] 14336

PC:~ Account$ PING ( 56 data bytes
.PC:~ Account$..Request timeout for icmp_seq 18851

But when I'm looking to activity monitor (on Mac) I see that the ping-process has PID 14337, but why does the variable contains then 14336 and how to fix it?

  • Why do you grab bashpid instead of $? ? – Jeff Schaller Nov 24 '16 at 16:12
  • Sounds a bit like you're getting the PID of the 'sudo' command. – mabako Nov 24 '16 at 16:13
  • @JeffSchaller dont you mean - why not $$ ? Looking at the answer below I am thinking bash is doing some things differently than I am used to (ksh user rather than bash) – Michael Felt Nov 24 '16 at 16:41

$BASHPID is the PID of the current bash process. You are looking for $!; see man bash, especially special parameters and job control. Also, ping needs sudo only if you are using -f (flood). Using sudo may complicate things, because as far as bash knows you are running sudo, not ping, therefore $! will return the PID of sudo.

$ ping -c 5 www.example.com & echo "The PID of ping is $!" ; sleep 6
[1] 4022
The PID of ping is 4022
PING www.example.com ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=0.260 ms
64 bytes from icmp_seq=2 ttl=64 time=0.329 ms
64 bytes from icmp_seq=3 ttl=64 time=0.382 ms
64 bytes from icmp_seq=4 ttl=64 time=0.418 ms
64 bytes from icmp_seq=5 ttl=64 time=0.434 ms

--- www.example.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4000ms
rtt min/avg/max/mdev = 0.260/0.364/0.434/0.066 ms
[1]+  Done                    ping -c 5 www.example.com
  • Flood ping (-f) may need superuser privileges. – trosos Nov 24 '16 at 16:35
  • You are right. I have edited my response to say this. – AlexP Nov 24 '16 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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