Home > database >  How to start a new bash REPL with executing a script
How to start a new bash REPL with executing a script

Time:05-23

I have a script foo.sh with some functions I'd like to test in a bash REPL, and for some reason I need to do this in a new bash REPL instead of sourcing it in the current shell, that is:

  1. Open up a new bash REPL
  2. Source foo.sh in the new-opened REPL

Is there such a way to do that in one command, like in python -i foo.py or ghci foo.hs? I have tried bash -i "foo.sh", bash -c "source foo.sh", bash -c "$(cat foo.sh)" etc., but all of them seem to just execute the script and then immediately exit.

CodePudding user response:

bash -c ". foo.sh && bash"

Example

foo.sh:

export TEST=MORE

Then run:

> bash -c ". foo.sh && bash"
> echo $SHLVL # shows how many shell levels we are down; 
2             # 2 because of the first and second `bash`
> echo $TEST
MORE          # yes, environment was sourced

PS: you could just run . foo.sh && bash but that would change your current environment, which, I assume, is what you want to avoid.

CodePudding user response:

You can use the --init-file option to do this (along with the -i option to mark the shell as interactive):

bash bash --init-file foo.sh -i

Note that -i must come after --init-file (and the filename).

  • Related