Is it considered good practice, when writing sh scripts, to unset all previously defined global variables at the end of the script?
If for example, I execute my script myscript using the . (source) builtin, like this
. myscript
after executing the script the shell is poluted with the variables defined in the script. This seems really bad (especially if used by other people).
If I could, I would get rid of globals in sh (or bash) altogether but more often then not they are the least worst solution :-).
This isn’t really executing the script. It is sourcing it, which makes the shell execute each command inside the script. If you want to execute the script, you would do this:
And in that case, none of the environment variables that are set inside the script would have an effect on your shell.
If you really need to source the script, so that it can do things like set environment variables or change your current directory, then you can isolate the variables inside a sub-shell using parentheses:
If you were to unset the variables you use, you would have the opposite problem. If a variable with the same name had been set by the user, then you would end up destroying it.