Say I have a command that puts me into a subshell (e.g. nix-shell). If I have a bash script that goes

echo hi

the echo hi will wait to be executed until I exit the subshell. Is there any way to write a script that behaves the same as manually typing out both lines in order? In other words, subsequent commands get executed in the newly invoked shell?

Edit: it seems what I'm looking to do doesn't have a general solution.

  • 1
    what is "enter-subshell"? if it's "nix-shell" there is a solution. if it is different the may be a different solution.
    – Jasen
    Mar 10, 2021 at 3:00
  • Are you looking for the --run option to nix-shell? nix-shell --run "echo hi"
    – Kusalananda
    Mar 13, 2021 at 22:14

1 Answer 1


You'll have to create a script and invoke that shell calling your script as a parameter. For example:

$ echo "echo hi" > my_echo.subshell
$ echo "enter-subshell -c my_echo.subshell" > my_script.bash
$ ./my_script.bash

The way to pass parameters to the subshell (in my example "-c") will depend on your subshell, each shell might use a different parameter.

As an alternative, if you don't want to create a second script, you can also redirect instructions to the shell. It will also vary and depend on the shell you want to call. For example:

enter-subshell -e <<EOF
echo hi

For this method, you can read more on "Here Documents". Again, you will find the proper way of executing the specific subshell (in my example "-e").

  • You're probably going to want <<'EOF' for another shell script. Mar 10, 2021 at 3:20
  • @MichaelHomer I think parsing of the outside script takes precedence, doesn't it? I'm not sure.
    – msb
    Mar 10, 2021 at 3:23

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.