How to unset envrionment variable from background in linux?
You can set a trap in parent process and unset it inside the trap while setting the background process to deliver a signal after specified time.
asd=foo
trap 'unset asd' SIGUSR1
p=$BASHPID
( sleep 1; kill -SIGUSR1 $p ) &
echo $asd # will print foo
sleep 2
echo $asd # will print empty line
Note that it will not unset a variable "exactly" after the specified time, but when the handler for the signal gets executed.
I guess alternatively I could imagine patchin bash and writing a bash builtin command that would create a thread that after specified time would unset the variable. Note that setenv
is not thread safe, so such setup would have to synchronized with other bash code.
What do I wrong?
You did unset the variable in a subshell. Subshell environment doesn't affect parent shell.