Are functions equivalent to built in commands in the bash / shell scripting language?

Example

$ echo "This is great"
This is great
$ num2=2
$ num3="Three"
$ echo $num2
2
$ echo $num3
Three

Redefining echo:

$ echo(){ command echo "The command was redefined"; }
$ echo $num2
The command was redefined
$ echo $?
The command was redefined

So is this true? Are all commands in Unix shell functions and we can manipulate them like that?

Answer

No, all Unix commands are not shell functions, but they may be overridden by a shell function.

Shell function names are not restricted by the names of built-in or external utilities. Just as you may have several external utilities with the same name under different paths, you may also have a shell function or an alias with that same name.

If there is a function called foo and a external or built-in utility called foo as well, then the function foo will be called.

To force the shell to pick the built-in utility, use

builtin foo

To avoid using the function foo, use

command foo

To guarantee that an external utility is used instead of a shell function, alias or built-in utility, use the full path to it, e.g.

/bin/echo

Aliases and functions occupy the same namespace, so you can’t have an alias and a function with the same name.


In short:

Unix commands may be

  • aliases, or
  • shell functions, or
  • utilities built into the shell, or
  • external utilities (compiled binaries or scripts written in any scripting language).

Some “commands” are not commands but keywords, such as for and if etc. These may also be overridden by aliases and shell functions for extra exciting shell experiences (i.e. don’t do that).

Leave a Reply

Your email address will not be published. Required fields are marked *