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

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@}"

If it's the bash shell, do:

unset $(compgen -v myvarname)

For example, show all variables in my current environment beginning with the letter 'S':

unset $(compgen -v  S)

Output:

SAL_USE_VCLPLUGIN
SCREEN_NO
SECONDS
SESSION
SESSIONTYPE
SHELL
SHELLOPTS
SHLVL
SSH_AUTH_SOCK

If it's a POSIX shell, try something more generic:

unset $(env | sed -n 's/^\(S.*\)=.*/\1/p')

Or if GNU grep is available:

unset $(env | grep -o '^S[^=]*')

Try this -

unset $(env | grep string |awk -F'=' '{print $1}')

Let say I have environment variable like -

printenv
string1=hello
string2=vipin

and when you will search with string grep will fetch both environment and fetch the name of environment variable and pass to unset command.

Tags:

Shell

Bash