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