Search code examples
bashsudopm2

How to sudo su; then run command


Can anyone help me to to solve following issue

i need to ssh to another server by e.g. ubuntu user which has permission to run sudo su fore sure then execute pm2 restart command

full command look like this

#!/bin/sh
CMD="sudo su; pm2 restart 0; pm2 restart 1; exit;"  
ssh -i somepemfile.pem ubuntu@1.1.1.1 $CMD

for example i can run normally any command with sudo

CMD="sudo /etc/init.d/apache2 restart"  

but with sudo su case it somehow hang and do not response


Solution

  • Unless you have an unusual setup, you can't normally string su with other preceding commands like that. I would imagine it is running sudo su, then hanging in the root environment/session, because it's waiting for you to exit before preceding to the pm2 commands. Instead, I would consider something along the lines of this using the -c option:

    CMD="sudo su -c 'pm2 restart 0; pm2 restart 1'"
    ssh -i somepemfile.pem ubuntu@1.1.1.1 "$CMD"
    

    As suggested in another answer, it would also probably be useful to encapsulate the $CMD variable in quotes in the ssh call.