bashterminalcommand-linescriptingcommand-line-interface

Extract Variable Name for Unset Script


I have a .env file that contains information, to include environment variables. For example:

# comment
<mini script>

export NAME="John Doe"
export LOCATION="US"
export TZ_LOCAL="NY"

When ran, I am able to have these environment variables; however, when done, a script runs to unset the environment variables.

This is the snippet that does such:

unset $(grep 'export' env | awk 'BEGIN { FS = "=" }; { print $1 }' | awk 'BEGIN { FS = " " }; { print $2 }')

This seems a bit much. Is there a simpler way to get the variable name after export and stop at the equal sign?

This snippet works, but seems like there should be a much simpler way than my snippet with multiple pipes.


Solution

  • Use space and = as input field separator:

    unset $(awk -F '[ =]' '/^export .*=/{print $2}' env)