Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "unsource" in bash?

Tags:

bash

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?

like image 334
Benjamin Avatar asked Jan 06 '12 15:01

Benjamin


People also ask

Can a Bash script modify itself?

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.

Does Bash ignore whitespace?

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.

How do I change environment in Bash?

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.

Do spaces matter in Bash?

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.


2 Answers

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 
like image 92
William Pursell Avatar answered Sep 18 '22 17:09

William Pursell


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.

like image 40
Celada Avatar answered Sep 18 '22 17:09

Celada