Override a builtin command with an alias

て烟熏妆下的殇ゞ 提交于 2020-07-20 07:20:06

问题


I am trying to make an alias that overrides the cd command. This is going to execute a script before and after the "real" cd.

Here is what I have so far:

alias cd="echo before; cd $1; echo after"

This executes the echo before and echo after command however it always changes directory ~

How would I fix this?

I also tried cd(){ echo before; cd $1; echo after; } however it repetedly echos "before".


回答1:


I also tried cd(){ echo before; cd $1; echo after; } however it repetedly echos "before".

because it calls recursively the cd defined by you. To fix, use the builtin keyword like:

cd(){ pwd; builtin cd "$@"; pwd; }

Ps: anyway, IMHO isn't the best idea redefining the shell builtins.




回答2:


Just to add to @jm666's answer:

To override a non-builtin with a function, use command. For example:

ls() { command ls -l; }

which is the equivalent of alias ls='ls -l'.

command works with builtins as well. So, your cd could also be written as:

cd() { echo before; command cd $1; echo after; }

To bypass a function or an alias and run the original command or builtin, you can put a \ at the beginning:

\ls # bypasses the function and executes /bin/ls directly


来源:https://stackoverflow.com/questions/28783509/override-a-builtin-command-with-an-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!