0

I am trying to run a script on a remote machine via ssh. For this I want to change the directory and run the script from there. I found that the standard method on how to do this is:

ssh -Y -t user@server 'cd dir; exec bash'

However, the problem is that prior to running my script I need to setup some further scipts which I do in my ~./bashrc. My problem is that the way the command is written the change of directory happens before the ~./bashrc is even executed, i.e. messing up the code I need to set up before. Note: changing the command to

ssh -Y -t user@server 'exec bash; cd dir'

executes the bash normally, but doesn't change the directory afterwards. Thanks in advance.

  • How about adding cd dir at the end of the .bashrc? – Panki Jul 19 at 12:47
  • @Panki But I also want to run a script as a command which I dont want to run every time I open a new shell – Mark Jul 19 at 13:12
1

My problem is that the way the command is written the change of directory happens before the ~./bashrc is even executed

It's more likely that ~/.bashrc doesn't get read at all. Bash only reads ~/.bashrc if it's invoked as an interactive (non-login) shell. When you give a command to run on the ssh command line, it executes the shell with the -c option, which makes it non-interactive.

But you can work around that by sourcing .bashrc manually:

ssh -t user@server '. ~/.bashrc; cd dir; exec bash'

Some bashrc files check if the shell is interactive, and only do changes if it is. (That sounds unnecessary, since bashrc is only read from an interactive shell, but because of the way Bash's startup files work, bashrc is also often sourced from .bash_profile or equivalent.)

To work around that, you'll need to force an interactive invocation of Bash, like so:

ssh -t user@server 'bash -ic "cd /tmp; exec bash"'

Manually sourcing .bashrc shouldn't be necessary now, since -i makes Bash do it itself. The second Bash (from exec bash) also does it, so if that's a problem, replace the last part with exec bash --norc.

...

It would probably be a good idea to split the relevant setup to a different file (say, .thingy.rc). Then source that from .bashrc (if necessary) and from the SSH command in stead of .bashrc.

  • You may need to invoke an interactive shell manually if bashrc checks for it. – muru Jul 19 at 14:43
  • @muru, hmm yes, that's annoying. – ilkkachu Jul 19 at 15:08
0

What about a here document, something like below:

ssh user@server << EOF exec bash       
cd dir
EOF
  • Does that do anything useful? The shell that starts gets the here-doc as its standard input, reads the cd command from it, and then exits when the here-doc ends. – ilkkachu Jul 19 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.