Automagically execute a bash function/cmd upon entering a directory.

After growing tired of sourcing Petalinux/Yocto-project settings everytime I needed to create/config a project, I decided to compile a script/code that resides under my ~/.bashrc , the only thing the code/script does it automagically source my settings upon entering the directory else it will just list the contents of that directory.

source $HOME/.opt/Xilinx/Vivado/2017.2/settings64.sh
export YOCTODIR=$HOME/Documents/Xilinx/EmbeddedLinux/Yocto/poky
export PETADIR=$HOME/Documents/Xilinx/EmbeddedLinux/Petalinux
function cd {
    # The 'builtin' keyword allows you to redefine a Bash builtin without
    # creating a recursion. Quoting the parameter makes it work in case there are spaces in
    # directory names.
    builtin cd "$@"
    if [ "$PWD" == "$YOCTODIR" ] ;
        then
            bash $YOCTODIR/.source_yocto
    elif [ "$PWD" == "$PETADIR" ] ;
        then
            bash $PETADIR/.source_petalinux
    else
        ls -lhF;
    fi
}

The content of source_petalinux listed above.

$ cat $PETADIR/.source_petalinux

#!/bin/bash
source ~/.opt/petalinux/settings.sh

as well as .source_yocto

$ cat $YOCTODIR/.source_yocto

#!/bin/bash
source $HOME/Documents/Xilinx/EmbeddedLinux/Yocto/poky/oe-init-build-env