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.

3 Answers 3

47

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.

2
  • 3
    I wonder, would adding -l option to bash be helpful as well? ... && exec bash -l
    – konsolebox
    Aug 16, 2013 at 4:55
  • 1
    @konsolebox: That's a good idea. I have added that to my answer.
    – user26112
    Aug 16, 2013 at 11:14
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?

4
  • 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, 2013 at 1: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, 2013 at 4:54
  • 5
    >& and &> are the same in Bash. The latter style is preferred though.
    – user26112
    Aug 16, 2013 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, 2013 at 1: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'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .