How to directly SSH to a specific directory and execute commands on a Linux server?

By | June 18, 2020

Have you ever been in a situation like this? Use the SSH command to enter the server, use the CD command to enter the corresponding directory, and continue your work. This is especially common for novices. In this article, the veteran driver will take you to a more efficient operation, just one step to achieve the desired results. Moreover, it is possible to access a specific directory on a Linux server quickly, but it is also possible to execute a command whenever you connect to the server.

Low-efficiency method:
If you don't know the method in this article, you probably have done it in the following two steps:
Step 1: Use the SSH command to enter the remote server

Step 2: Use the CD command to get to the directory you want

cd <some-directory>

Use only one command to log into a specific directory

The method, as mentioned above, is certainly possible, but it is too inefficient. You need to use two commands to do this, but you can use one command to achieve the same goal:

ssh -t [email protected] 'cd /home/ubuntu/test; bash'

Using this command, we can go directly to the corresponding directory in a remote server (i.e., /home/ubuntu/test). Then you can continue your work.
In this case, the -t option is meant to force pseudo-terminal allocation even if the standard input is not terminal. If you don't, there may be a prompt like this:

Pseudo-terminal will not be allocated because stdin

In addition, you can use the following command:

ssh -t [email protected] 'cd /home/pi/tests ; exec bash'

or

ssh -t [email protected] 'cd /home/pi/tests && exec bash -l'

Here, the -l option sets this bash to the login shell. In the above three commands, the last parameter is bash, because my remote server's default shell interpreter is bash. If you don't know what shell interpreter your remote server is using, use this command:

ssh -t [email protected] 'cd /home/pi/tests && exec $SHELL'

Directly SSH to a specific directory and execute commands on a Linux server using only one command

As mentioned at the beginning of this article, you can not only use a command to go to a remote server specified directory, but you can also use a command to execute a server command remotely. We can even use a command to enter the remote server's specified directory and then execute another command.

The method is the same. For example, if we want to go to the /home/pi/tests directory of raspberry PI and execute the lS-AL command, we can enter the command as follows:

ssh -t [email protected] 'cd /home/pi/tests && ls -al && exec $SHELL'