Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a bash variable each time the directory changes

Tags:

bash

path

prompt

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?

like image 344
Tom Avatar asked Aug 29 '12 09:08

Tom


2 Answers

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\/}
}
like image 153
Rody Oldenhuis Avatar answered Oct 19 '22 16:10

Rody Oldenhuis


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
}
like image 1
perreal Avatar answered Oct 19 '22 14:10

perreal