Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unset variables after use in .zshrc?

Tags:

variables

zsh

So let's say I set a bunch of variables in my .zshrc:

function print_color () {      echo -ne "%{\e[38;05;${1}m%}";  }  # color guide: http://misc.flogisoft.com/_media/bash/colors_format/256-colors.sh.png RED=`print_color 160` DEFAULT="%{$fg[default]%}"  PROMPT='$RED%${DEFAULT} $ ' 

The problem is these remain set, once I am actually running commands

$ echo $RED %{%}            # With colors, etc. 

How would I unset them after use in my .zshrc? What is the best practice here?

Thanks, Kevin

like image 282
Kevin Burke Avatar asked Jul 29 '14 16:07

Kevin Burke


People also ask

How do you unset a system variable?

To unset an environment variable from Command Prompt, type the command setx variable_name “”. For example, we typed setx TEST “” and this environment variable now had an empty value.


1 Answers

Unsetting a parameter is done with the built-in unset

unset PARAMETER 

unsets PARAMETER. This can be done as soon as you no longer need PARAMETER, at the end of the file or anywhere inbetween.

"Best practice" depends highly on the use case:

  • In the case of colors you probably want them to be available from top to bottom, so that you can use the same colors in the whole file. Therefore you probably want to unset them near bottom of ~/.zshrc.
  • If you are just storing some output for a few lines of code, which you do not need in any other part of the file, you can unset it immediately after the last usage or at the end of the block of code in question.

Also, if you need a parameter only inside a function, you can declare it with local

function foo () {     local PARAMETER     # [...] } 

It will then be only available inside this function without the need for unset.


That being said, in this case you actually need RED to be available in your running shell as it is needed each time your prompt is evaluated (everytime just before it is printed). This is due to PROMPT being defined in single quotes (and the shell option PROMPT_SUBST being set, see output of setopt | grep promptsubst).

If you do not intend to change RED during runtime just put it in double quotes when defining PROMPT:

PROMPT="$RED"'%${DEFAULT} $ ' 

This will substitute $RED when PROMPT is defined and only ${DEFAULT} each time PROMPT is evaluated.

After that you can just do unset RED. Note that there must be no $ before RED, else the shell would substitute it by the value of RED and try to unset a parameter named like the value:

% FOO=BAR ; BAR=X % echo "> $FOO | $BAR <" > BAR | X < % unset $FOO % echo "> $FOO | $BAR <" > BAR |  < % unset FOO % echo "> $FOO | $BAR <" >  |  < 
like image 130
Adaephon Avatar answered Sep 25 '22 02:09

Adaephon