Run ssh and immediately execute command

BashUnixSsh

Bash Problem Overview


I'm trying to find UNIX or bash command to run a command after connecting to an ssh server. For example:

ssh name@ip "tmux list-sessions"

The above code works, it lists the sessions, but it then immediately disconnects. Putting it in the sshrc on the server side works, but I need to be able to type it in client side. I want to be able to run a command, it logs in, opens up the window, then runs the command I've set. Ive tried

[command] | ssh name@ip

ssh name@ip [command]

ssh name@ip "[command]"

ssh -t name@ip [command]

Bash Solutions


Solution 1 - Bash

ssh -t 'command; bash -l'

will execute the command and then start up a login shell when it completes. For example:

ssh -t user@domain.com 'cd /some/path; bash -l'

Solution 2 - Bash

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

Solution 3 - Bash

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncadlacView Question on Stackoverflow
Solution 1 - BashBarmarView Answer on Stackoverflow
Solution 2 - BashgypaetusView Answer on Stackoverflow
Solution 3 - BashKeith ThompsonView Answer on Stackoverflow