Run shell script when navigating to directory with cd
Solution 1
One of the ways you can do this is via alias
command:
alias cdgit="cd /foo; git status"
Then you execute cdgit
and you go to directory /foo
and exec git status
Solution 2
You can replace cd
with a function which adds any processing you want:
cd() {
builtin cd "$@"
# Do whatever you want here
}
Solution 3
I use something similar to Stephen Kitt's answer in my .bashrc
:
function cd() {
command cd "$@" || return
if [[ -d .git ]]
then
git status --short
else
ls -al
fi
}
You can create additional conditions to handle different things as needed.
NOTE: since we're clobbering the reference to the cd
command, you have to use command cd
, builtin cd
, or \cd
to prevent the function from calling itself and recursing forever. For this reason some might find it useful to rename this function.
Related videos on Youtube
OlehZiniak
Updated on September 18, 2022Comments
-
OlehZiniak over 1 year
Is it available to set script to run in a particular directory, when you
cd
into it?For example if
/foo
is a directory withgit
project, is it possible, whencd /foo
automatically rungit status
or somenpm
scripts?Please don't link answer to strictly to
git
, imagine that could be any other command/script.-
Gilles 'SO- stop being evil' about 7 yearsFor the git part, you may want to adapt unix.stackexchange.com/questions/320671/…
-