I have sourced a script in bash source somescript.sh
. Is it possible to undo this without restarting the terminal? Alternatively, is there a way to "reset" the shell to the settings it gets upon login without restarting?
EDIT: As suggested in one of the answers, my script sets some environment variables. Is there a way to reset to the default login environment?
One of the requirements I have is that the script must be self contained; no other files are to accompany the script and there are to be no environment variables. This would require the script to be able to edit itself.
Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
The lack of spaces is actually how the shell distinguishes an assignment from a regular command. Also, spaces are required around the operators in a [ command: [ "$timer"=0 ] is a valid test command, but it doesn't do what you expect because it doesn't recognize = as an operator.
It is typically sufficient to simply re-exec a shell:
$ exec bash
This is not guaranteed to undo anything (sourcing the script may remove files, or execute any arbitrary command), but if your setup scripts are well written you will get a relatively clean environment. You can also try:
$ su - $(whoami)
Note that both of these solutions assume that you are talking about resetting your current shell, and not your terminal as (mis?)stated in the question. If you want to reset the terminal, try
$ reset
No. Sourcing a script executes the commands contained therein. There is no guarantee that the script doesn't do things that can't be undone (like remove files or whatever).
If the script only sets some variables and/or runs some harmless commands, then you can "undo" its action by unsetting the same variables, but even then the script might have replaced variables that already had values before with new ones, and to undo it you'd have to remember what the old values were.
If you source a script that sets some variables for your environment but you want this to be undoable, I suggest you start a new (sub)shell first and source the script in the subshell. Then to reset the environment to what it was before, just exit the subshell.
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