How can I ssh directly to a particular directory?

Frosty picture Frosty · Mar 9, 2009 · Viewed 177.3k times · Source

I often have to login to one of several servers and go to one of several directories on those machines. Currently I do something of this sort:

localhost ~]$ ssh somehost

Welcome to somehost!

somehost ~]$ cd /some/directory/somewhere/named/Foo
somehost Foo]$ 

I have scripts that can determine which host and which directory I need to get into but I cannot figure out a way to do this:

localhost ~]$ go_to_dir Foo

Welcome to somehost!

somehost Foo]$

Is there an easy, clever or any way to do this?

Answer

rogeriopvl picture rogeriopvl · Mar 9, 2009

You can do the following:

ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted ; bash --login"

This way, you will get a login shell right on the directory_wanted.


Explanation

-t Force pseudo-terminal 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.

  • If you don't use -t then no prompt will appear.
  • If you don't add ; bash then the connection will get closed and return control to your local machine
  • If you don't add bash --login then it will not use your configs because its not a login shell