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?
In my very specific case, I just wanted to execute a command in a remote host, inside a specific directory from a Jenkins slave machine:
But my machine couldn't perform the ssh (it couldn't allocate a pseudo-tty I suppose) and kept me giving the following error:
I could get around this issue passing "cd to dir + my command" as a parameter of the ssh command (to not have to allocate a Pseudo-terminal) and by passing the option -T to explicitly tell to the ssh command that I didn't need pseudo-terminal allocation.
You could add
to your
.bashrc
file (or.profile
or whatever you call it) at the other host. That way, no matter what you do or where youssh
from, whenever you log onto that server, it willcd
to the proper directory for you, and all you have to do is usessh
like normal.Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".
I've created a tool to SSH and CD into a server consecutively – aptly named sshcd. For the example you've given, you'd simply use:
Let me know if you have any questions or problems!
You can do the following:
This way, you will get a shell right on the directory_wanted.
Explanation
-t
then no prompt will appear.; bash
then the connection will get closed and return control to your local machineSSH itself provides a means of communication, it does not know anything about directories. Since you can specify which remote command to execute (this is - by default - your shell), I'd start there.
Based on additions to @rogeriopvl's answer, I suggest the following:
Chaining commands by
&&
will make the next command run only when the previous one was successful (as opposed to using;
, which executes commands sequentially). This is particularly useful when needing tocd
to a directory performing the command.Imagine doing the following:
The directory
teminal
doesn't exist, which causes you to stay in the home directory and remove all the files in there with the following command.If you use
&&
:The command will fail after not finding the directory.