46

I frequently login to a server, then cd into a specific directory. Is it possible to simplify these two commands into one?

ssh bob@foo  
cd /home/guest

I'd like to avoid changing anything on 'foo' if possible, as I'll have to clear it with the server administrator. I use bash, but I am open to answers in other shells.

spuder
  • 18,053

3 Answers3

48

This works with OpenSSH:

ssh -t bob@foo 'cd /home/guest && exec bash -l'

The last argument runs in your login shell. The -t flag passed to ssh forces ssh to allocate a pseudo-terminal, which is necessary for an interactive shell. The -l flag passed to bash starts bash as a login shell.

25

Just put as the last line of your ~bob/.bash_profile file on foo:

cd /home/guest >& /dev/null

Now each time you log in (whether by SSH or otherwise), the cd command will run. No mucking around with ssh is necessary.

I know you wrote that you'd "like to avoid changing anything on 'foo' if possible," but if the bob@foo account is yours, changing your own .bash_profile should be acceptable, no?

DanB
  • 486
  • 2
    Why yes, I think this will work great. I won't need to get permission from IT to make that change. Could you elaborate on why you need >& /dev/null ? – spuder Aug 16 '13 at 01:41
  • 6
    I think that should be &> /dev/null. It prevents any error message that may be shown just in case cd fails to change directory to /home/directory. If you want to see those messages you could just exclude that. – konsolebox Aug 16 '13 at 04:54
  • 5
    >& and &> are the same in Bash. The latter style is preferred though. –  Aug 16 '13 at 11:16
  • Additionally, the redirection to /dev/null prevents the name of the directory from being echoed onscreen, which "cd" may do. – DanB Sep 11 '13 at 01:40
18

You can also do it this way, similar to @EvanTeitelman's solution:

$ ssh -t bob@foo "cd /tmp ; bash"

Or if you don't know the shell on the other end:

$ ssh -t bob@foo "cd /tmp && exec \$SHELL"

Or like this:

$ ssh -t bob@foo 'cd /tmp && exec $SHELL'
slm
  • 369,824