Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make some shell calls automatically when entering a directory?

Tags:

bash

shell

sh

Just like a local .bashrc file, which is sourced every time I entered the directory. How to make this work?

like image 895
flyingfoxlee Avatar asked Dec 26 '22 01:12

flyingfoxlee


2 Answers

You can use an alias:

$ echo 'echo "execute something for $PWD"' > tests/.cdrc
$ _cd()
{
    \cd $1
    [ -r .cdrc ] && . .cdrc
}

this function first change to the dir specified as argument, check if the file .cdrc is readable and source it.

$ alias cd=_cd

Then

$ cd tests
execute something for /path/to/tests
like image 98
Diego Torres Milano Avatar answered Jan 13 '23 17:01

Diego Torres Milano


bash and zsh (and probably many other shells) have a feature that allows you to run an arbitrary command before the prompt is displayed. You can use this to source a .dirrc file, and it won't break tab completion.

Here's how to do it in bash:

PROMPT_COMMAND='
if [ "${PREV}" != "$(pwd -P)" ]; then
    if [ -r .dirrc ]; then
        . ./.dirrc
    fi
    PREV=$(pwd -P)
fi
'

From the bash man page:

PROMPT_COMMAND: If set, the value is executed as a command prior to issuing each primary prompt.

This is how to do it in zsh (see the zshmisc man page):

precmd() {
    if [ "${PREV}" != "$(pwd -P)" ]; then
        if [ -r .dirrc ]; then
            . ./.dirrc
        fi
        PREV=$(pwd -P)
    fi
}
like image 23
Richard Hansen Avatar answered Jan 13 '23 15:01

Richard Hansen