One‑Liner SSH Tricks: Jump Directly to a Remote Directory and Run Commands
Learn how to streamline remote Linux workflows by using a single SSH command with the -t option to automatically change to a target directory, execute commands like ls or bash, and even customize .bashrc for automatic directory navigation, eliminating the need for separate cd steps.
Typical two‑step SSH workflow
Users often connect to a remote Linux host and then issue a separate cd command to reach the working directory.
ssh user@remote-system
cd /path/to/dirOne‑liner with pseudo‑terminal allocation
Adding the -t option forces SSH to allocate a pseudo‑terminal, allowing a command string to be executed immediately after login. The remote shell can be started with exec $SHELL (or bash) so the session remains interactive.
ssh -t user@host 'cd /desired/path ; exec $SHELL'Variations
Keep an interactive Bash after changing directory:
ssh -t user@host 'cd /desired/path && exec bash'Start a login shell (the -l flag makes Bash behave as a login shell):
ssh -t user@host 'cd /desired/path && exec bash -l'Chain additional commands, e.g., list files before opening a shell:
ssh -t user@host 'cd /desired/path && ls -al && exec $SHELL'Detecting the remote default shell
If the remote host does not use Bash, you can query the current shell after login with echo $SHELL or ps -p $$ and adjust the command string accordingly.
Alternative: modify .bashrc on the remote host
For users who prefer not to type a long command each time, a permanent cd can be added to the remote user's ~/.bashrc file.
vim ~/.bashrc
# Append the following line
cd /home/pi/tests >/dev/nullAfter saving, either source the file ( source ~/.bashrc or . ~/.bashrc) or start a new SSH session; every new login will automatically change to the specified directory.
Caveats
The .bashrc method is static—changing the target directory requires editing the file again. The one‑liner approach with -t is more flexible for occasional tasks because the directory can be changed on the fly without modifying remote configuration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
