Search code examples
shellunixsu

Need script to continue when switching over to new user


SO I have this script that will ssh you onto a new system, switch into a new user, and then I need it to execute three more commands while under that user. This is how I have it setup right now.

ssh -t $7 'cd /home/install/ ; su -c bash install ; tar -xvf [tarball] ; cd [directory] ; ./execute install ; bash'

What it will do is switch my user to the install user, but once there it doesn't execute any of the following commands. Only after I exit out of the install and back into the root user will those final commands run.

So for a tldr; I need a way to run those last three commands as the install user.

Thank you for your time! :)


Solution

  • You have two problems: 1. Your quotes are getting interpreted away 2. You're not using su correctly

    If you want su to execute commands as that user, you have to provide them in STDIN, e.g. echo 'cd; ls' | su user. However, to do that, you're going to need to escape some stuff.

    If the command you want to run as the user install is:

    cmd1; cmd2; cmd3
    

    Therefore, you provide it to su like so:

    echo 'cmd1; cmd2; cmd3' | su install
    

    However, you also want to execute it over ssh, which means you have to escape the quotes in the first sequence:

    ssh user@host 'echo \'cmd1; cmd2; cmd3\' | su install'