Reputation: 569
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
Upvotes: 23
Views: 11041
Reputation: 8446
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[^=]*')
Upvotes: 14
Reputation: 172698
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@}"
Upvotes: 42
Reputation: 3147
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.
Upvotes: 9