Bash – ssh change user and execute command

bashssh

This is my command that I have in my script:

ssh -i $KEY $USER@$HOST "sudo su tom; echo $DATA >> /home/user/file.txt

These commands work fine on there own but together in the script it just hangs.

If you run this command by itself sudo su tom; cat /home/user/file.txt
It will only execute cat when you logout of the user tom.

How do you change user and execute a command in a bash script ?

Best Answer

In addition to what Paul Calabro suggested, which I don't think is your main problem , you should define what command-line interpreter(shell) to use for execute the command on the remote machine, since there could be a different shell from localhost.

I think you will also need the -t param of ssh command:

-t Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

Something as follow should get closer to what you are looking for:

ssh -it $KEY $USER@$HOST 'sudo su tom; echo $DATA >> /home/user/file.txt; bash'

Unfortunately, in the above solution the "concat" of sudo su && echo still doesn't work, but using -c parameter of su command should fix

-c, --command=COMMAND pass a single COMMAND to the shell with -c

Related Question