Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a bash function upon entering a directory

Tags:

I'd like to execute a particular bash function when I enter a new directory. Somethink like:

alias cd="cd $@ && myfunction" 

$@ doesn't work there, and adding a backslash doesn't help. I'm also a little worried about messing with cd, and it would be nice if this worked for other commands which changed directory, like pushd and popd.

Any better aliases/commands?

like image 486
Paul Biggar Avatar asked Jul 29 '10 08:07

Paul Biggar


People also ask

How do I run a shell script from a different directory?

To use full path you type sh /home/user/scripts/someScript . sh /path/to/file is different from /path/to/file . sh runs /bin/sh which is symlinked to /bin/dash . Just making something clear on the examples you see on the net, normally you see sh ./somescript which can also be typed as `sh /path/to/script/scriptitself'.

How do I execute a bash script?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

How do I go to a specific directory in bash?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.


2 Answers

Aliases don't accept parameters. You should use a function. There's no need to execute it automatically every time a prompt is issued.

function cd () { builtin cd "$@" && myfunction; } 

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.

The Bash docs say:

For almost every purpose, shell functions are preferred over aliases.

like image 115
Dennis Williamson Avatar answered Sep 21 '22 17:09

Dennis Williamson


The easiest solution I can come up with is this

myfunction() {   if [ "$PWD" != "$MYOLDPWD" ]; then     MYOLDPWD="$PWD";     # strut yer stuff here..   fi }  export PROMPT_COMMAND=myfunction 

That ought to do it. It'll work with all commands, and will get triggered before the prompt is displayed.

like image 38
falstro Avatar answered Sep 19 '22 17:09

falstro