DEV Community

Garett Dunn
Garett Dunn

Posted on • Originally published at garettmd.com on

Unset All Variables Matching a Pattern

Unset all variables beginning with prefix

When using the Openstack CLI, you typically will get a shell script that you would source, which will export a bunch of variables to your session. I’ve run into the problem of switching between two different Openstack installs that were on different versions, and needed different variables. I had issues where variables from one instance were still there when trying to use another one. I could go ahead and remove them one by one, but I didn’t get into this line of work to do things by hand. Accordingly, the following example will unset all Openstack variables (all variables that begin with OS_)

For bash it’s

# Bash
unset "${!OS_@}"
Enter fullscreen mode Exit fullscreen mode

Because it’s bash, it’s a cryptic incantation of symbols that only wizened old graybeards can explain. (that's sarcasm)

For zsh it’s

# zsh
unset -m "OS_*"
Enter fullscreen mode Exit fullscreen mode

As you can see, in zsh it’s much simpler. You use the -m flag (I believe it stands for “match”) then use a glob match. I’m not sure if it supports regex or not, because for some reason the documentation for zsh builtins is not easy to find.

Obviously, you can use this for a lot of things. I tend to use this a lot with CLI tools (Openstack, AWS, Terraform, etc). Hopefully it’s useful for you!

Top comments (0)