I'm using ssh to connect to a remote Linux machine like this:

ssh -i .ssh/path/to/id_rsa -p 22 user@host 'cd /path/to/dir'

I'd like some commands to be executed upfront (such as cd /path/to/dir) and then proceed with my own business, but I get logged out right away after the commands are run. Any way to stay logged in?

  • Not a duplicate. cd /path/to/dir is just an example. I've got more than just one command to execute. – Desmond Hume Sep 23 '14 at 13:58
  • In that case, please edit and clarify. However, since you have cross-posted this on U&L, please leave this one closed and edit the one there instead. – terdon Sep 23 '14 at 13:58
  • @terdon I'm deleting the one on U&L – Desmond Hume Sep 23 '14 at 14:01
  • As you wish but since this one is closed... Anyway, please clarify how many commands you need to run. The simplest approach would probably be to add them to a script and call that script from your .profile on the remote server. – terdon Sep 23 '14 at 14:03
  • @terdon About three commands. I'd rather not split scripting logic across two machines. – Desmond Hume Sep 23 '14 at 14:06

Specify your shell afterwards so that runs. You also need the -t flag for a proper shell experience. So you end up with something like:

ssh ... -t user@host 'cd /path/to/dir; /bin/bash'

As terdon suggests in the comments, if you have a big stack of commands that you want to run every time you connect to this server as this user, you probably want to edit your .profile or .bashrc to run the commands automatically.

  • It works but user@host prompt is missing.. – Desmond Hume Sep 23 '14 at 13:56
  • Yeah, just remembered (finding a question of mine) that you need to throw in the -t flag. – Oli Sep 23 '14 at 13:57

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.