Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash execute a shell function after a change directory (cd)

Trying to find a way to execute a function within BASH after changing into a directory.

for example,

# cd code/project/blah
"Your latest modified files are main.cc blah.hpp blah.cc"
(~/code/project/blah) # _

With the above I'm hoping to be able to wrap other functionality around the bash command.

Was hoping to find something along the lines of zsh hook functions http://zsh.sourceforge.net/Doc/Release/Functions.html#SEC45

like image 894
battlemidget Avatar asked Dec 28 '22 09:12

battlemidget


2 Answers

Don't forget about pushd and popd, unless you never use them. I'd do this:

PS1='(\w) \$ '
chdir() {
    local action="$1"; shift
    case "$action" in
        # popd needs special care not to pass empty string instead of no args
        popd) [[ $# -eq 0 ]] && builtin popd || builtin popd "$*" ;;
        cd|pushd) builtin $action "$*" ;;
        *) return ;;
    esac
    # now do stuff in the new pwd
    echo Your last 3 modified files:
    ls -t | head -n 3
}
alias cd='chdir cd'
alias pushd='chdir pushd'
alias popd='chdir popd'
like image 178
glenn jackman Avatar answered Jan 05 '23 16:01

glenn jackman


You could make an alias for cd which executes the standard cd and then some function that you've defined.

like image 24
Nate W. Avatar answered Jan 05 '23 18:01

Nate W.