Unable to override PS1 with direnv

2k Views Asked by At

I am following the direnv wiki on PS1. I have the following relevant entries in my files.

.bashrc

DEFAULT_PS1='\[$(ppwd)\]\u@\h:\w$(__git_ps1 " (%s)")'
# add some more things to DEFAULT_PS1, conditionally
DEFAULT_PS1+='> '

PS1=${CUSTOM_PS1:-$DEFAULT_PS1}

# optional bashrc file extensions
for f in ~/.bashrc_*; do test -s $f && . $f || true; done

eval "$(direnv hook bash)"

.envrc

export KUBECONFIG=~/.config/kube/homelab.yaml
export KUBE_PS1_ENABLED=on
export CUSTOM_PS1='$(kube_ps1) $ '
PATH_add scripts

I have allowed the latest version of the .envrc with direnv allow. However, when changing to the directory, the custom PS1 value is not set, although the values seems to be right

$ cd -
/home/robert/sources/oss/sling-cloud-native
direnv: loading .envrc
direnv: export +CUSTOM_PS1 +KUBE_PS1_ENABLED ~KUBECONFIG ~PATH

$ echo $PS1
\[$(ppwd)\]\u@\h:\w$(__git_ps1 " (%s)")$(kube_ps1)>

$ echo $CUSTOM_PS1
$(kube_ps1) $

I am not sure how the solution in the wiki is supposed to work, as apparently the value of PS1 is set to the DEFAULT_PS1 when the .bashrc file is loaded the first time and is not re-evaluated as part of the direnv hook.

How can I change the value of PS1 using direnv?

1

There are 1 best solutions below

1
On

The direnv wiki mentions that the author had to "blacklist PS1 as an environment variable that can be changed," mainly because "The core issue is that PS1 is a local variable." So I don't think workarounds that involve using the .envrc file to indirectly modify the PS1 can work.

I had a similar issue with python virtual environments, which I realize is different to your use case, but there is an example in this blog that could be helpful.

Because links can die I reproduce it here:

  1. add the following to ~/.bashrc (me: I tested this with ~/.zshrc and it also works)
show_virtual_env() {
  if [[ -n "$VIRTUAL_ENV" && -n "$DIRENV_DIR" ]]; then
    echo "($(basename $VIRTUAL_ENV))"
  fi
}
export -f show_virtual_env
PS1='$(show_virtual_env)'$PS1
  1. Then source the file again
source ~/.bashrc

The wiki also mentions adding unset PS1 to the .envrc file, which removes any error about direnv: PS1 cannot be exported... and I can confirm that also works with this scenario.

Perhaps you can do something similar; use .envrc to export the environment variables as you are doing, but remove the line export CUSTOM_PS1='$(kube_ps1) $ ' and in your ~/.bashrc make a function that checks if you have set KUBE_PS1_ENABLED and appends '$(kube_ps1) $ ' to PS1 if it is set.