23

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

3

3 Answers 3

43

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@}"
Sign up to request clarification or add additional context in comments.

Comments

14

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[^=]*')

2 Comments

-v is for all shell variables (exported as well as local). -e is for exported/environment variables, so that's probably what the OP wants since they are using env. See unix.stackexchange.com/questions/151118/…
@wisbucky, This works: nn1=foo nn2=bar nn3=baz ; compgen -v n, but this does not nn1=foo nn2=bar nn3=baz ; compgen -e n. Please elaborate if there's more to it...
9

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.

1 Comment

env | awk -F= '{print $1}' can give false-positive results when env values are multi-line strings. compgen -e returns only the env names

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.