Any ideas why this happens?
cd. You're executing
commands; bash, so
bash starts in whatever directory
The obvious solution is to
cd back just before you invoke
ssh -t $server 'commands; cd "$HOME"; exec bash -l'
- Single quotes prevent expanding
$HOME locally; in case you need
commands to include locally expanded variables, mix the quotes (e.g.
"commands with $var; "'cd "$HOME"; exec bash -l').
exec, because you don't need the parent shell on the remote side anymore (or do you?).
-l (equivalent to
--login) because sole
ssh $server spawns a login shell and you want your entire command to act alike. Bash as a login shell sources different file(s) than as non-login shell, starting with
/etc/profile; the rules are somewhat complicated, see
man 1 bash, look for
INVOCATION. If one of these files performs
cd to another directory, you'll get what you get even if
commands don't change the directory. You didn't tell what the directories ("right" one and "wrong" one) are, so it's hard to even guess what the purpose of this "hidden"
cd may be.
Or you can run
commands in a subshell. This won't affect the working directory of the parent shell so
bash will start wherever the parent shell starts:
ssh -t $server '(commands); exec bash -l'
You may prefer one solution or the other depending on what
commands do. For example if
commands modify the environment of their shell on the remote side then running them in a subshell or not makes a difference for the final