7

I would like a variable available my bash shell similar to pwd but equal to a section of the current working directory, rather than the whole path.

i.e.,

$PWD=/a/b/c/d/e/f  
$PATH_SECT=c/d/e

I have a prompt that displays this path already, but I would like to update a variable in the environment to this value each time I change directory.

How could I do this?

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
Tom
  • 702
  • 7
  • 16

2 Answers2

5

You could use the promptcmd function. From man bash we learn that this function is executed just prior to showing the prompt. It's empty by default (or rather, not defined).

A simple example:

promptcmd(){
    local p=$(pwd)
    PATH_SECT=${p/\/a\/b\/}
}
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
1

You can use an alias and a function in your .bashrc:

alias cd="supercd"  # call the function
function supercd(){
  builtin cd "$@"   # original cd
  PATH_SECT=$(pwd)  # or whatever
}
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
perreal
  • 94,503
  • 21
  • 155
  • 181