I'm trying to add ()
around my Python virtual environment name like this:
(my-env) my-user@my-machine:%
and if the env is not set, it will only show:
my-user@my-machine:%
Right now I have:
MYPS1 ='($PYENV_VERSION) '
which will show the ()
if the virtual env is not set:
() my-user@my-machine:%
Is there away I can do something like this:
MYPS1 ='($PYENV_VERSION) ' if $PYENV_VERSION exists else ''
CodePudding user response:
So the important thing when setting the prompt like this, is that you (probably) want to reevaluate it every time it prints the prompt. That way if and when the envvar changes, the prompt changes. That's why you have '
characters around what you're adding to the prompt -- it prevents any vars or code in there from being evaluated when you set it. While you could do something like you suggest (with an if
in the shell) that would not be reevaluated when the prompt was printed, so could be "stale".
Instead you want to do it all in the variable expansion. sh/bash comes with a variety of ways of expanding variables but the one you want is
${parameter: word}
Use Alternative Value. If parameter is unset or null, null is substituted; otherwise, the expansion of word is substituted.
That means you want something like
MYPS1 ='${PYENV_VERSION: ($PYENV_VERSION) }'