I would like to spawn a bash subshell from a bash script that allows me to initialize environment variables and do some tasts so that when the script ends the user is in the subshell with the initialized environment variables.
By testing I found out that if I have the instruction /bin/bash in the script, the subshell is spawned and the user is in the subshell when the script ends. If I execute exit, the subshell terminates and the user is back in the parent shell.
I now would like to be able to initialize environment variables and do some tasks in the subshell based on arguments given in the script.
How could I achieve that ?
exec is what you are looking for
$ cat reshell.sh
#!/bin/bash
export MY_ENVIRONMENT=foo
chdir /home/bar
exec $SHELL
where the exec replaces the currently running script with a new shell that has inherited the environment of the script. This will still be a subordinate shell to the one that you ran it from, but it will be only one layer deep; for example:
$ pwd
/home/chmike
$ ./reshell.sh
$ pwd
/home/bar
$ exit
$ pwd
/home/chmike
Using exec $SHELL instead of exec /bin/bash allows the script to invoke the user's preferred shell in case it isn't bash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With