Opposite of the `source` command

Using a subshell (Recommended)

Run the source command in a subshell:

(
source linuxmachines_mount_point.txt
cmd1 $linuxmachine02
other_commands_using_variables
etc
)
echo $linuxmachine01  # Will return nothing

Subshells are defined by parens: (...). Any shell variables set within the subshell are forgotten when the subshell ends.

Using unset

This unsets any variable exported by linuxmachines_mount_point.txt:

unset $(awk -F'[ =]+' '/^export/{print $2}' linuxmachines_mount_point.txt)
  • -F'[ =]+' tells awk to use any combination of spaces and equal signs as the field separator.

  • /^export/{print $2}

    This tells awk to select lines that begin with export and then print the second field.

  • unset $(...)

    This runs the command inside $(...), captures its stdout, and unsets any variables named by its output.


You cannot unsource the script.

What you can do is to store all exported variables in a temporary file, compare it with variables after the script is sourced, and then removed overflow with unset, e.g.:

export > temp_file
source myscript

#... do some stuff

unset "$(comm -3 <(sort temp_file) <(export | sort) | awk -F'[ =]' '{print $3}' | tr '\n' ' ')"

You can use unset command to "forget" variables.