Home > Blockchain >  Bash: How to set changing variable in PS1 and preserve PS1 codes like \w
Bash: How to set changing variable in PS1 and preserve PS1 codes like \w

Time:08-21

I'd like the include a dynamic variable in my PS1 prompt, let's say the 5th folder in the path. I'd also like to include some other PS1 codes (maybe color, username or current directory).

I have a script to get the 5th folder and echo it with one of the escape PS1 codes.

demo_prompt.sh

folder5=$(cut -d / -f 6 <<< $PWD)<br>
echo "$folder5 \W $ "

This .bashrc sets PS1 to the output of the script.

.bashrc

PS1='$(~/demo_prompt.sh)'

If I keep the PS1 definition in .bashrc in single quotes:

Pro: The 5th folder dynamically updates while I change directories as desired,
Con: \W appears in the prompt rather than resolving to the current folder name.

If I change the PS1 definition in .bashrc from single quotes to double quotes:

Pro: \W resolves properly to be the current directory
Con: The 5th folder is fixed to the value when I source .bashrc

How can I achieve both the \W resolving and the 5th folder dynamically updating?

I've more or less followed the idea here and am essentially asking the followup question that went unanswered. Bash: How to set changing variable in PS1, updating every prompt)
Quote: "I.e. it won't read in the escape codes nor color options. Any suggestions on this one?"

Thanks!

CodePudding user response:

Try this :

demo_prompt.sh

folder5='$(cut -d / -f 6 <<< $PWD)\n'
echo "$folder5 \W $ "

and .bashrc

PS1="$(~/demo_prompt.sh)"

CodePudding user response:

PROMPT_COMMAND='dir5=$(cut -d / -f 3 <<< "$PWD")'
PS1='$dir5 \W $ '

(Note the quotes)

PROMPT_COMMAND runs before the prompt is displayed and allows you to set global variables. You can also set it to a function call that would set global variables, call scripts, or call your script directly from PROMPT_COMMAND.

  • Related