Last background process ID ($!) not working in sudo bash command

خرید بک لینک

Do shell variables work inside sudo executed commands?

I'm trying to run, and later kill, a background process, as another user inside a script. However, I cannot capture the background process ID, with "$!", which means I cannot later kill the process.

Here is a simple example I've put together to illustrate:

#!/bin/bash
userOfThisScript=`id -u -n $SUDO_USER`

sudo -u $userOfThisScript /bin/bash << EOBLOCK
    vi &
    echo "BG Task ID inside block:  <$!>" # <-- $! is empty string
    kill $!
EOBLOCK

Running the background process works fine. Checking the process executed (e.g. with "ps") I can confirm that the process is indeed owned by the user given to sudo. However, the $! variable is just an empty string (as far as I can tell).

If I remove the sudo/bash block and just execute the process and kill it, then all works as expected with a correct process ID stored in $!.

Anyone have any idea why $! does not work inside this sudo/bash command execution?

(I'm using Linux/Ubuntu distros, 14.04 and 16.04.)

Recent Questions...

ما را در سایت Recent Questions دنبال می‌کنید

برچسب: نویسنده: استخدام کار بازدید: 220 تاريخ: دوشنبه 7 تير 1395 ساعت: 2:23

صفحه بندی