Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux terminal: Run command when changing directory

I work in a Linux environment where certain modules need to be loaded for different work areas. These are separated by individual filesystem directories.

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

like image 803
devshans Avatar asked Jan 23 '13 16:01

devshans


3 Answers

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

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

Here your custom command can be anything that will execute specific commands according to the directory you enter.

The alias declared afterwards makes sure that typing 'cd' will invoke the function and the real cd command.

edit: An example for your need

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
}

Explanation:

We create a variable containing the parent of the directory you want to enter. Then we retrieve the parent's parent. Then we create the script name in the grandparent directory.

Then the executability of this filename is checked, if so, the script is executed, and finally the real cd command is executed.

Be careful to define the function before the alias, else it will cause an infinite recursion !

like image 107
SirDarius Avatar answered Sep 29 '22 02:09

SirDarius


You could make a function to run those special commands.

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

Then you call that function along with cd with another function for example.

cd2() {
  cd $1
  run_command
}

cd2 /path/to/somewhere
like image 33
lmcanavals Avatar answered Sep 29 '22 00:09

lmcanavals


a pretty vague question, but I think the alias command might help you:

alias cd='echo "hello $1"'

this will display hello <arg given to cd> when you try to cd somewhere

like image 20
Tudor Constantin Avatar answered Sep 29 '22 01:09

Tudor Constantin