views:

62

answers:

4

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

+3  A: 

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

Shakedown
A: 
alias cd='echo DO SOME WORK; cd $*'
sha
No, `$*` is used in functions, not aliases.
glenn jackman
+2  A: 

Use PROMPT_COMMAND. You should have a look at git-sh, which includes a lot of fancy git-related tricks and should also be easy to learn from.

Daenyth
This is also very helpful, but I couldnt mark 2 things as answers :(Thanks!
SimmaDoWN
+1  A: 

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'
glenn jackman