0

I've been working on bash script and have encoutered strange issue. Basically, I SSH into remote server as root from local server and trying to run some commands. One of the commands is changing the user to service account from root. For that I use command "su " and it changes to service account. But strangely, when I run the same command inside 'if condition', it remains as root account only. Here's the snippet of the code:

  echo "Enter host name you want to start: "
  read remote

  echo "Enter password for $remote : "
  read -s remote_pass

  sshpass -p$remote_pass ssh -T -o StrictHostKeyChecking=no $remote <<EOF
      ps -ef | grep -i tomcat | grep -i bootstrap | awk '{print \$2}'

      if [ -z "\$(ps -ef | grep -i tomcat | awk '{print \$2}')" ]
        then
          echo "$remote: Need to start server"
          su serviceAccount -----------> This doesn't work inside if controller
          startup.sh ---------> I want to run this script using serviceAccount and not as root!!!
        else
          echo "$remote: Already up and running"
      fi
      echo "#######################################################"
      echo
EOF

Please help!

Thanks, Sid

1 Answers1

2

This is not strange but expected. su is not some kind of magic toggle, instead it spawns a new process with elevated rights. Everything you would like to do as serviceAccount needs to be done within the su call.

For non-interactive use like in your example, the -c option comes handy:

su -c 'startup.sh' serviceAccount
ypnos
  • 50,202
  • 14
  • 95
  • 141
  • Thanks for the solution. I'm fairly new on this. I have a question, when in do 'su' before the if loop, the whole code below works as serviceAccount. But not when I log inside the if loop. That's what I found strange. – Siddharth Gandhi May 13 '20 at 14:12
  • 1
    It would work the way you describe if you put the `su`command in front of your '< – ypnos May 13 '20 at 16:40