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.
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 !
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With