Reputation: 2222
Let's say I have a script install.sh
.
I want to put a command at the beginning of this script that will clean the environment for me, keeping only $PATH and $HOME of a parent shell.
I know about env -i
but it requires a second script which will do "env -i install.sh". I want a single install.sh script which users will run directly ("sh install.sh" or "./install.sh").
Upvotes: 0
Views: 618
Reputation: 30841
One way to do this is to use compgen -v
to give a list of variable names, and unset each in turn:
for i in $(compgen -v)
do
case "$i" in
HOME|PATH)
;;
*)
unset "$i"
;;
esac
done
unset i
Note that there are some Bash variables which can't be unset:
BASHOPTS
BASH_ARGC
BASH_ARGV
BASH_LINENO
BASH_SOURCE
BASH_VERSINFO
EUID
PIPESTATUS
PPID
SHELLOPTS
UID
_
Upvotes: 1
Reputation: 4897
You can re-exec the script from within it:
[ -z "$CLEANED" ] && exec env -i CLEANED=1 "PATH=$PATH" "HOME=$HOME" bash "$0" "$@"
unset CLEANED
Where CLEANED
is a marker variable to tell your script that the environment has been cleaned.
Upvotes: 3