Revert '.' or 'source'

No, there is no general method for undoing the effects of sourcing a script (or even of "merely" executing one). This is a corollary of the fact that there exist irreversible commands (e.g. file deletion). If your script contains an irreversible command then the effects of sourcing that script will also be irreversible.


Is there any way to 'unsource' it or in other words to revert it and restore previous environment?

No, there is no automatic way in general.

However we don't know what you source-ed. Perhaps it is simple enough to be trivial to undo (e.g. something which just change your PATH from a previously well known one).


If you know ahead of time that you'll want to do this, you can do the source command in a subshell, and revert its effects (insofar as they're scoped to setting shell or environment variables) by exiting that subshell.

Thus, if you run:

(source set-variables; run-command-with-variables); run-command-without-variables

...then run-command-with-variables will have those variables set, but run-command-without-variables will not.


It's also possible to identify which shell functions were set by sourcing a script by checking metadata associated with those functions, such that one could theoretically write a shell function or sourceable script that unsets all other functions defined within a given (parameterized) file. For non-function variables, however, there is not information stored to permit them to be unset (much less identifying prior values).