1

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!

Rob
  • 13
  • 1
  • 1
  • 2

2 Answers2

0

Try this :

demo_prompt.sh

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

and .bashrc

PS1="$(~/demo_prompt.sh)"
Philippe
  • 20,025
  • 2
  • 23
  • 32
  • Ah ha, I had to single quote the line in demo_prompt.sh. Thanks! I guess without the quote it was immediately resolving the variable and now it's passing the string itself upstream to be resolved later. – Rob Aug 23 '22 at 20:19
0
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.

root
  • 5,528
  • 1
  • 7
  • 15