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?
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'.
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.
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.
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.
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.
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