4

I have an alias that connects to my development server:

alias sshDev='ssh -p 22 username@ip_address'

I'd like to be able to both connect and automatically switch to a new directory:

cd ../my-favorite-directory

Is there anyway to run both commands under one local alias?

lese
  • 2,726

1 Answers1

4

you can alias the command as follow :

alias sshDev="ssh -tp 22 username@ip_address 'cd /path/to/dir; bash'"

As Arthur2e5 suggested adding parameters -il is convenient

related part in man bash:

   -i        If the -i option is present, the shell is interactive.
   -l        Make bash act as if it had been invoked as a login shell (see INVOCATION below).

If you wish to have a dynamic destination folder (define it each time you call the alias) you will have to write a function called by your alias. E.g.:

alias sshDev=ssh·Dev

function ssh·Dev() {

  if [ "$#" -eq 0 ]; then
    fav_dir="/path/to/dir"
  else
    fav_dir=$1
  fi

  ssh -tp 22 username@ip_address "cd $fav_dir; bash"

}

With this little piece of code, when you call(type) the alias in your command line as follow: sshDev (without parameters) , it will use the statical /path/to/dir defined in the function , otherwise if you call the alias like this sshDev /one/other/path/to/dir will use the path provided in-line.

lese
  • 2,726
  • 1
    Maybe cd blah; exec bash -il is better. – Mingye Wang Oct 15 '15 at 13:43
  • Yes it works too, can you please explain why it is better? thank you – lese Oct 15 '15 at 13:50
  • Can I ask what the final bash does? – Eric Oct 15 '15 at 14:07
  • Nice question, I'm not completely sure but I guess it define what command-line interpreter(shell) to use for execute the command on the remote machine, since there could be a different shell from localhost – lese Oct 15 '15 at 14:17
  • @lese I think that that sounds like a reasonable explanation. Also, I'd like to accept your answer, but I'm not seeing the typical "checkmark"; if it ever does appear, I will accept it! – Eric Oct 15 '15 at 14:49
  • I've just finish to edit the post, If you want to give an other look at the function, I adapted it in order to be dynamic if wanted, and static if no path in input is given. I think I see why you can't accept the answer, you asked the question with an account, and now you are logged in with an other account, I see it from different username in your comments : ) – lese Oct 15 '15 at 14:54
  • 1
    Good edit! And, what you say about the account makes sense; I was too quick to the mark and should have used my normal stackoverflow account, I think. – Eric Oct 15 '15 at 14:58