Taking a step back & building to a final answer (fwiw the question as stated seems unnecessarily complicated due to artificial, albeit extremely common, administrative/managerial restrictions, so perhaps reframing the question might provide easier work-arounds):
First, you can change your default shell on the remote host (without root) by using chsh -s /bin/bash
(or whatever your path to your preferred bash
is, eg /opt/local/bin/bash
) and put your start-up commands in ~/.bash_login
or ~/.bashrc
as appropriate (google the precedence rules, but caveat: you may see different behavior across versions of bash + OS, so do test; maybe it's less of an issue today, but in particuar, macOS and older Unix (Solaris) have caused problems for me in the past.) If you actually have root access, just use usermod
to change your default shell on the remote (but if this is the case, the question doesn't make sense.)
Along those same lines, to ssh
into the remote and start an interactive bash
session, using bash -l
will cause the init scripts to run for a login shell (eg ~/.bash_login
, ~/.bash_profile
, ~/.bashrc, again, check the rules for precedence, defaults & fallbacks.) Specifically,
$ ssh -t user@host '/path/to/foo.sh; bash -l'
But note that any commands causing env changes before bash -l
won't be in your shell. Not unless they're in the remote init files (~/.bashrc
, etc).
So, finally, instead of running the default init files on the remote, you can specify the init file in the bash
command, in order to set up your remote env, have those changes stay in your bash
shell:
$ ssh -t user@host 'bash --init-file ~/my_env.sh'
where ~/my_env.sh
replaces your ~/.bashrc
(or whatever). If you also want the ~/.bashrc
to run, just "include" (aka "source") it inside your my_env.sh file (ie: . ~/.bashrc
).
Lastly, if the ~/my_env.sh
file isn't actually physically on the remote, you can pass arbitrary commands via process substitution (to "generate" the init file dynamically):
$ ssh -t user@host 'bash --init-file <(echo "export FOO=bar; source /path/foo.env")'
However, as the syntax <( commands )
is specific to bash
, you'll need to either use the comparable syntax in the default remote shell, or run that command in bash (presents an interesting problem in escaping quotes):
$ ssh -t user@host 'bash -c "bash --init-file <(echo \"export FOO=bar; source /path/foo.env\")"'
At this point, you're logged into the remote, a remote bash
shell is running, and FOO
should be bar
, and the remote /path/foo.env
will still be in effect in the current shell. (Optionally source your remote ~/.bashrc
, but careful about weird things that may not work, eg fancy prompt PS1
stuff, but I digress.)