To achieve the dynamic update of your shell prompt to display the current and parent directory names in every new shell session without the need to change directories, you can use a small script in your .bashrc
that sets the PS1
variable. The issue with your current approach is that it sets PS1
to the result of the expansion at the time of sourcing .bashrc
, but it doesn't dynamically update PS1
after that unless the directory changes.
To ensure PS1
updates dynamically with every command, you can use a shell function that recalculates PS1
before displaying the prompt. Bash provides a mechanism for this through the PROMPT_COMMAND
environment variable. This variable can be set to a command that executes before the display of each prompt.
Here's how you can do it:
prompt_command() {
# Capture the current working directory
local cwd="${PWD}"
# Extract the last two components of the path
local last_two_dirs="${cwd#"${cwd%/*/*}/"}"
# Set PS1 with these components
PS1="${last_two_dirs} $ "
}
# Set PROMPT_COMMAND to call the prompt_command function
PROMPT_COMMAND=prompt_command
Here's a breakdown of what this script does:
- Defines a function prompt_command that dynamically calculates the last two components of the current working directory and sets
PS1
accordingly.
- Sets
PROMPT_COMMAND
to call this function before each prompt is displayed. This way, PS1
is recalculated before showing the prompt, reflecting the current and parent directories accurately.
To use this script:
- Open your
.bashrc
file in your favorite text editor. For example, you can use nano ~/.bashrc
or vim ~/.bashrc
.
- Copy and paste the above script into your
.bashrc
file.
- Save the changes and exit the editor.
- To apply the changes to your current terminal session, source your
.bashrc
file by running source ~/.bashrc
.
Now, your command prompt should dynamically display the current and parent directory names in every new command line prompt, updating correctly even in new shell sessions without the need to change directories first.