0

While being a root, I want to start a service as a specific user and write its PID file. Minimal nonworking example:

if [ $UID -eq 0 ]; then  
su myuser <<EOF 
sleep 30 &  
echo $! >mypid.pid  
EOF
fi  

After execution file mypid.pid is empty, $! is empty too, but there is a process sleep for my user with assigned pid (obviously). I pressume it is because a new shell is spawned and somehow it does not track its history. Is there any way I can make it work?

1 Answer 1

0

Because you feed the shell invoked by su(1) from a script, $! gets interpreted by the script calling su(1). The way to prevent this is to escape $!, then $! does get fed to the shell invoked by su(1) and not the calling script:

if [ $UID -eq 0 ]; then  
su myuser <<EOF 
sleep 30 &  
echo \$! >mypid.pid  
EOF
fi  

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .