Wednesday, February 2, 2022

[SOLVED] How to SSH to remote server and cd into source directory in one step - BASH

Issue

I have multiple repos on my remote server like this:

sourcecode/

  • repoA
  • repoB
  • repoC

Each time I have to work on the remote machine on a repo (say repoA), I do two things:

  1. ssh to remote-server
  2. cd sourcecode/repoA on remote

Instead of doing this all the time, I would like to be able to have an alias / function on my Mac such that when I do "ssh-with-fancy-function" and pass argument: repoA , it should ssh into the remote server and after that is complete, should change my current directory on the remote server to sourcecode/repoA and stay.

How can I do this ?


Solution

ssh_cd() {
  if (( $# != 1 )); then
    echo "usage: ${FUNCNAME[0]} remote_dir" >&2
    return 1
  fi
  printf -v cmd 'cd %q && bash -i' "$1"
  ssh -t user@remote-host "$cmd"
}

The key here is that you end the command with bash -i to start an interactive shell; and the -t ssh option to ensure you have a tty to interact with. This assumes your remote shell is bash.



Answered By - glenn jackman
Answer Checked By - Cary Denson (WPSolving Admin)