Score:2

How to shorten current working directory in bash prompt dynamicaly

tr flag

So I'm looking for a way to shorten the path in the prompt if it reaches a defined length, such as:

user1@localhost:~/Pictures/awesome_trip/

Would be fine, but if we cd into more sub-directories such as:

user1@localhost:~/Pictures/awesome_trip/first_day/mikes_camera/funny_pics

I would like the prompt to change to

user1@localhost:/.../funny_pics

I know how to change the prompt in the .bashrc

I was wondering if there is a way to make it dynamically such that I can get the current length of the working dir and check the length, and change the prompt. something along the lines of:

CUR_PROMPT=$(pwd); # get the working dir

CUR_PROMPT_LENGTH={#CUR_PROMPT}; # get the length

if[ $CUR_PROMPT_LENGTH -gt 20 ]; then 
  # if prompt is long, render shorter version
  PS1='\u@\h:...\w:\$';
else
  # else render long version
  PS1='\u@\h:\W:\$'

Hopefully there is way to do this, Thank you for your answer.

hr flag
The bash shell already implements a `PROMPT_DIRTRIM` mechanism for that - see [How can I shorten my command line (bash) prompt?](https://askubuntu.com/a/459355/178692)
Telegonicaxx avatar
tr flag
@steeldriver This is exactly what I was looking for. I can't believe i did not come across it while googling it. Thank you!
Score:0
cn flag

You can use something like the code below. Just add it to your .bashrc file in your home folder. It will basically make your prompt resemble "user@computername [dir] $" so it might look like telegonicaxx@laptop [shared] $

export PS1="\u@\h [\W] \\$\[$(tput sgr0)\]"

You can generate your own prompt style and colors using the website linked below

http://bashrcgenerator.com/

Telegonicaxx avatar
tr flag
Thank you @Roxana, this is really neat website, thank you for sharing it. Not exactly what I was looking for though
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.