Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a builtin command with an alias

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".

like image 634
iProgram Avatar asked Feb 28 '15 15:02

iProgram


People also ask

How do I override an alias?

The backslash escape character before a shell command disables and override any shell aliases.

Does alias override path?

If a shell is involved, aliases take precedence over $PATH lookups. Of course, later alias definitions can override earlier ones. If no shell is involved or no alias by a given name exists, $PATH lookups happen in the order in which the directories are listed in the variable.

How do I run a command without alias?

Use a “\” (backslash) before the command to run it without the alias. The backslash escape character can be used before a shell command to override any aliases.

Can aliases be used in Bash scripts?

BASH Alias is a shortcut to run commands using some mapping. It is a way to create some shortcut commands for repetitive and multiple tasks. We create an alias in a BASH environment in specified files. We can also incorporate BASH functions, variables, etc to make the Alias more programmatic and flexible.


2 Answers

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

or use command itself:

command ls
like image 120
codeforester Avatar answered Oct 06 '22 15:10

codeforester


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.

like image 30
jm666 Avatar answered Oct 06 '22 16:10

jm666