Bash – Source a file after ssh login drops to prompt

bashsourcesshzsh

One-liner question: How do I automatically source a remote file on remote host after logging in via SSH via a bastion host?

I need to source a file containing a list of aliases + shell user defined functions on a remote host after ssh-ing into it.

The file exists on remote maching in /tmp folder e.g. /tmp/my-rc

Searching other posts and internet I have found

ssh -t user@domain.com 'source /tmp/my-rc; bash -l'

The problem is that I do get a terminal, but none of the aliases are set since it's a new bash shell'

Thinking, that the source should be done after the shell is attached, tried the below but this also doesn't work. There is no error, I get the terminal but don't think the file got sourced (verified by echoing dummy message from /tmp/my-rc file)

ssh -t user@domain.com 'bash -l; source /tmp/my-rc'

Even tried with '.' instead of source, no luck.

Any help.

Note1: Bash or ZSH any shell solution would do.

Note2: The actuall ssh is via a proxy command i.e. a hop over bastion host (Just mentioning if it is relevant at all)

Note3: I don't have privilage of a profile rc or bashrc or even a home directory on the remote host.

Note4: The exact command that I used to login into the secure host is via bastion host like below

ssh -o ProxyCommand='ssh -W %h:%p ec2-3-218-12-120.compute-1.amazonaws.com' 10.0.31.122  

Best Answer

With bash, you can do:

ssh -t user@host '
  PROMPT_COMMAND="source /tmp/my-rc
                  unset PROMPT_COMMAND
                 " exec bash --norc'

Which would cause /tmp/my-rc to be sourced before the prompt, and only that prompt since we unset PROMPT_COMMAND afterwards.

You'll want to remove the unset PROMPT_COMMAND if /tmp/my-rc actually ends up defining it.

The above assumes the login shell of the remote user is Bourne-like, but you should be able to adapt it to most other types of shells (csh / rc / fish).

Related Question