Linux terminal: start command when changing directory

I work in a Linux environment where some modules need to be loaded for different workspaces. They are separated by separate file system directories.

I am wondering if there is an easy way to run different commands from 1 line when entering directories. I am flexible with the type of shell used, but currently I'm using C Shell.

+5
source share
3 answers

If you are using bash, I would recommend you create a function like this:

function custom_cd() { custom_command $1; cd $1; }
alias cd='custom_cd'

Here your user command can be any that will execute certain commands in accordance with the directory you entered.

An alias declared later ensures that entering 'cd' will call the function and the real cd command.

:

function custom_cd() {
    if [ -z "$1" ];
    then
        target=~
    else
        target=$1
    fi
    target=${target%/}
    parent=$(dirname `readlink -f $target`)
    grand_parent=`dirname $parent`
    script=$grand_parent/`basename $target`.sh
    if [ -x $script ];
    then
      `$script`
    fi
    cd $1
}

:

, , . . script grandparent.

, , script , , cd.

, , !

+6

.

run_command() {
  case `pwd` in
    "/path/to/dir1" )
      ...
      ;;
    "/path/to/dir2" )
      ...
      ;;
    ...
  esac
}

cd , .

cd2() {
  cd $1
  run_command
}

cd2 /path/to/somewhere
+3

, , alias :

alias cd='echo "hello $1"'

hello <arg given to cd>, cd -

+2

All Articles