DEV Community

chinmay chhajed
chinmay chhajed

Posted on • Edited on

Add current working directory in your shell prompt

Bash prompt can be set by setting the environment variable PS1.

Current directory can be displayed in 3 types:

  • Full path
~/work/esp/esp-idf/examples/bluetooth/nimble$ 
Enter fullscreen mode Exit fullscreen mode
  • Partial path
~/.../bluetooth/nimble$ 
Enter fullscreen mode Exit fullscreen mode
  • Only parent directory.
nimble$ 
Enter fullscreen mode Exit fullscreen mode

In value of PS1, \w or \W can be used to include working directory in the prompt. Change the value of PS1 in your $HOME/.bashrc file to change it for every terminal.

If you use zsh or any other shell, search where the config file is located and update it accordingly. .bashrc is used for bash shell which is default in most systems.

To set full path, \w can be used.

PS1="\w$ "
# Prompt would look like:
# ~/work/esp/esp-idf/examples/bluetooth/nimble$ 
Enter fullscreen mode Exit fullscreen mode

To see only current directory's name in prompt, use \W

PS1="\W$ "
# Prompt would look like:
# nimble$ 
pwd
# Prompt will show only first parent directory, current path is:
# /home/chinmay/work/esp/esp-idf/examples/bluetooth/nimble
Enter fullscreen mode Exit fullscreen mode

To see partial path, the environment variable PROMPT_DIRTRIM can be set to desired value to see number of parent directories. Default value of PROMPT_DIRTRIM is 0.

PS1="\w\$ " # Setting PS1 to show full path
# ~/work/esp/esp-idf/examples/bluetooth/nimble$ 
export PROMPT_DIRTRIM=4 # Trimming path to 4 directories
# ~/.../esp-idf/examples/bluetooth/nimble$ 
export PROMPT_DIRTRIM=2 # Trimming path to 2 directories
# ~/.../bluetooth/nimble$ 
export PROMPT_DIRTRIM=0 # Back to normal
# ~/work/esp/esp-idf/examples/bluetooth/nimble$ 
Enter fullscreen mode Exit fullscreen mode

Checkout designing a minimal bash prompt.

Top comments (0)