0

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?

marked as duplicate by Mitch Oct 1 '14 at 19:19

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.

2

The Problem

  • Using sudo inside a script often doesn't do what you expect (see Digital Chris' link: “How do I run this sudo command inside a script?”).
  • Sending sudo to the background will not work (correctly and reliably), if you need to provide a password.

The Solution

Retrieve the process ID inside the process spawned by sudo. If you use exec, you don't even need to use pgrep -P as a crutch. Create a shell script, say pid-badblocks.sh:

#!/bin/sh
echo $$
exec badblocks -o "$2" "$1"

Make it executable and invoke it with:

sudo ./pid-badblocks.sh <DEVICE> <OUTPUT>

This works, because exec replaces the current process with badblocks (in this case) while keeping the same process ID. We can therefore print the process ID of the shell process before invoking badblocks.

0

Guessing...

If each command works independently, it could be that the PROCESSID assignment happens too quickly.

Try adding 'sleep 3s' after 'sudo ...' and see what happens.

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