How to write a shell script that will reload terminal at middle of the script and then start using commands again?
Matthew Harrington
I recently knew about sdkman in gitpod.io and I wanna install different java versions using this manager. But I have a very old version of sdkman. That's I need to update it, then install java. But I don't wanna type this commands in my every repository in gitpod. That's why I have written an shell script prerequisites.sh and I will use this file in every repository. The script is:-
sdk update
sdk install java 17-open
# there are lots of command under this, but they're not necessary in this question.But then I knew that after updating sdkman, I need to restart terminal. I found that exec bash restarts terminal. But when I add exec bash in my shell script, it doesn't execute the commands below the exec bash command. Can someone suggest me, how to do this?
sdk update
exec bash #recently added, but doesn't execute the commands after it :(
sdk install java 17-open 1 1 Answer
The problem you are having is when you open a new shell or restart the current shell, your script will no longer be loaded in the new shell. So, what you need to do is:
- Open the parent shell
- Execute the first command
- Create a child shell within the parent script
- This child shell will be loaded with the new environment parameters
- Execute the second command within the child shell
- Exit child shell
- Exit parent shell
For the above mentioned commands, you can use something like this.
#!/bin/bash
sdk update
sudo su - $USER -c 'sdk install java 17-open'The first command will run in the parent shell. The second line (with sudod su - $USER) will open a new child shell within the same script, and execute the second command.
PS: You will be asked to enter the password, if you haven't configured "NOPASSWD" for sudo. Check this to setup that.