This question already has an answer here:
I have a little problem with a script of mine. I execute a command in background using sudo and I try to retrieve the PID of the command in a variable.
the code is the following:
#!/bin/bash sudo badblocks -o $2 $1 & PROCESSID=$(pgrep -P $!) echo $PROCESSID
I executed every command one by one in a shell and it works fine but when i launch the script it doesn't work. I've other command to obtain the PID such as "ps --ppid $! -o pid=" but it doesn't work either.
if you have any idea why?