Unset All Variables Matching a Pattern

Posted on Tue 02 April 2019 in articles

Note: I haven’t written anything in a while. It’s hard for me to sit and write a longer article, make sure it’s understandable, proofread it, yada yada. But then as I was going through all my “tech” notes, I realized I have a bunch of short articles already written. And I already take all my notes in Markdown. So they’re almost just a copy and paste operation. Anyway, that’s all to say I will be posting more often now, but they’ll be shorter (and more to the point). So hopefully this will work well.

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 "${[email protected]}"

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

For zsh it’s

# zsh
unset -m "OS_*"

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!