Bash – Override Commands

Bash – Override Commands : In this Bash Tutorial, we shall learn to override an inbuilt command using Bash Functions.

We may override commands in bash by creating a function with the same name as the command we would like to override. For example to overrideps  command, you have to create a function with nameps .

This could be helpful in  scenarios like you use a command with certain options, and you do not like to provide the whole command with options several times in your script. So you may override the command for command with options. Now let us learn how overriding commands could be done in Bash Shell Scripting.

Example – Bash – Override Command

In this example, we shall try overridingls  command forls -ltr .

#!/bin/bash

# override 'ls' command for 'ls -ltr'
ls () {
	command ls -ltr
}

ls
$ ./bash-override-command
total 8
-rwxrwxrwx 1 arjun arjun 82 Nov 21 16:41 bash-function
-rwxrwxrwx 1 arjun arjun 82 Nov 21 16:41 bash-override-command
ADVERTISEMENT

Example – 2 – Bash – Override Command

In this example, we shall try overridingecho  command, and add time stamp in from of the argument toecho  command.

#!/bin/bash

# override 'ls' command for 'ls -ltr'
echo () {
	builtin echo -n `date +"[%m-%d %H:%M:%S]"` ": "
	builtin echo $1
}

echo "Maverick Reporting. Over."
$ ./bash-override-command-echo 
[11-21 17:10:14] : Maverick Reporting. Over.

Conclusion

In this Bash Scripting Tutorial, we have learnt to override commands with the help of Example Bash Scripts.