bashshell

Unset all environment variables starting with a leading string while in a script (without closing or restarting Bash)


I'd like to:

unset myvarname*

where myvarname is a string and * is... well, you got it.

I tried

env | grep string | unset

But it doesn't work.

I'm into a script, and I don't want to start a new shell so no env -i or source something or leaving the reentering the shell


Solution

  • In the Bash shell, the ${!prefix@} parameter expansion generates all variables that start with prefix.

    ${!prefix@} Expands to the names of variables whose names begin with prefix [...] When @ is used and the expansion appears within double quotes, each variable name expands to a separate word.

    This list can then be passed to unset:

    unset "${!myvarname@}"