Overriding Commands in Bash

Overriding commands refers to making custom implementations of a built-in or external command. The best way to override a command is to use bash functions. You can also create aliases for the command you are trying to override. Moreover, manipulating the environment variable also offers a great way to achieve this task. Overriding commands is crucial when you want to execute a command with multiple options avoiding repetition.

This article will describe how to override commands in bash, why it’s significant, and how you can leverage it to enhance your workflow.

Why Do We Override Commands in Bash?

Overriding commands in Bash empowers users to develop customized commands, facilitating the streamlined execution of complicated commands. Let’s say, you want to run the ls command with -lih options and wish to avoid writing the whole commands repeatedly, just replace the command with ls to obtain a similar functionality by overriding it.

Here are a few reasons why you should override commands in bash:

  • Personalization: Overriding commands makes it possible to modify the behavior of the command according to the user’s preferences.
  • Improved Functionality: Overriding commands allows users to add more features to existing commands. For example, replacing the command “ls” with the command “ls -ilh” improves the performance of the command.
  • Enhanced Productivity: Overriding lets you create a shortcut for a long command that saves time and increases productivity.
  • Environment Management: When working with a particular version or project where command names are not different, you can override the command names to use your favorite one within the shell session or forever.
  • Troubleshooting and debugging: For troubleshooting and debugging purposes, users can customize commands temporarily.

How to Override Commands in Bash?

In Bash, you can enable 3 ways to override commands. Let’s explore each of them in detail:

1. Using Bash Function

Bash functions allow the users to override commands by creating a function name with the overridden command name or defining a function inside the “.bashrc” file. Here you go:

1.1 Overriding Commands Within Scripts

Creating a function with the same name as the command to override is the simplest way to make a customized command within a Bash script. In this example, the ls -lih command will be overridden by the ls command with the help of a Bash function. After that, whenever you call the ls command within the script, it will execute the ls -lih command. Here’s how:

#!/bin/bash 

#Script to override command using Bash function   
ls () { 
    command ls -lih  
}
ls
EXPLANATION

The script defines a function named ls. The command keyword inside the function allows the function to call the original “ls” command without recursing from the function itself. The -lih options are passed to the original ls command. Here, option -l displays all the files or directories with more detailed information (modification time, ownership, permissions, and size). The -i option shows the inode number of the files and directories. Finally, the -h option prints the sizes in human-readable format. Finally, after calling the ls function, it will execute the ls -lih command.

overriding commands using bash function

All the contents of the home directory are displayed with their inode number and human-readable file sizes.

Note: If you don’t write the keyword “command” inside the function before the ls -lih command, you’ll be stuck in an infinite loop. However, if you encounter this problem, press CTRL+C to exit out of the loop.

1.2 Overriding Commands Permanently in Terminal

To override commands permanently in the terminal, the function can be produced inside the “.bashrc” file making it permanent to shell sessions (does not end once the shell session terminates). For that purpose, open the .bashrc file using the nano command and follow the steps below:

  1. Type nano .bashrc in the terminal.
  2. Write the following script at the end of the file, changing the behavior of the pwd command:
    pwd() {
        echo "You are here: $(command pwd)"
    }
EXPLANATION

In this script, the function will print a message “You are here” along with the current working directory (output of the pwd command) using the command substitution $(command pwd). Every time you type the pwd command in your terminal, it will execute the pwd() function instead of the default pwd command.

  1. After writing the script inside the .bashrc file, type CTRL+S to save and CTRL+X to exit.
  2. To apply the changes made in the .bashrc file, source the file by writing the following command:
    source ~/.bashrc

    Now, you will get the following output for the pwd command:
    overriding commands permanently using bash function

Note: To get back the default output of the pwd command, you can delete or comment the relevant lines in the “.bashrc” file. Additionally, you can run the following command:

unset -f pwd

2. By Creating Aliases

In Bash, aliases can override commands by generating shortcuts or alternate names for commands either in the terminal or in the “.bashrc” file. This approach helps to save the user time and effort. Moreover, It helps to create a custom behavior for a specific command. Now, follow this command to understand how to create an alias for the grep command to override it:

alias grep='grep --color=auto'
EXPLANATION

This command creates an alias for the grep command. After typing the grep command in the terminal, it will execute the grep --color=auto (shows colorized output of the matched patterns) command instead of the default grep output (displays only the matched patterns).

Once you have created the alias for the grep command, run the following command to see the matched colorized patterns:

grep "Linuxsimply" file.txt

overriding commands by creating alias

The overridden command searches for the pattern “Linuxsimply” in the “file.txt” and displays the colorized pattern.

To make the alias permanent, consider writing the alias grep='grep --color=auto' command inside the “.bashrc” file. The overridden command will run even though the current shell session has ended.

Note: To get back the default output of the grep command, delete or comment the alias grep='grep --color=auto' line in the “.bashrc” file. You can also run the following command:

unalias grep

3. Using Environmental Variable

Consider using environmental variables in the custom script to override commands. This allows you to change the functionality of the command without changing the source code. To do this, follow the steps below:

  1. Create a Bash script you want to override. For instance, I am going to replace the default output of the date command by writing the following script inside the nano text editor:
    #!/bin/bash
    date "+%A, %B %d, %Y - %H:%M:%S"
    EXPLANATION

    The format string “+%A, %B %d, %Y – %H:%M:%S” specifies how the date and time should be represented. Here’s the breakdown of the format:

    • %A: Full weekday name (e.g., Monday, Tuesday).
    • %B: Full month name (e.g., January, February).
    • %d: Day of the month (01 to 31).
    • %Y: Year (e.g., 2024).
    • %H: Hour (00 to 23).
    • %M: Minute (00 to 59).
    • %S: Second (00 to 59).
  2. Make the script executable by typing chmod +x my_command.sh. Then, set an environmental variable named DATE that holds the path to the custom script:
    export DATE="/home/mou/my_command.sh"
  3. Now, create an alias “date” for the DATE environmental variable so that each time you enter the date command, the output from the “DATE” variable is executed:
    alias date="$DATE"
  4. Run the “date” command to see the custom output as follows:overriding commands by using environmental variable

Note: You can make the customized date command permanent by setting the environmental variable in the “.bashrc” profile.

How to Prevent Overriding Bash Function?

It is important to protect the override of the Bash function in order to keep the script’s integrity and avoid unexpected output. Here are some ways to do this:

1. Using “readonly” Attribute

Use “readonly” attribute to make the function read-only, protecting the function from being overridden. Here’s how you can do it:

readonly -f my_function

This command will prevent overriding the my_function by utilizing the readonly attribute.

2. Choosing Unique Names

Don’t use built-in command names as the function name. This will cause the function to be overridden. To make a function name unique, add unique identifiers or namespaces before the function name. For example: _my_function or my.function, etc.

3. Encapsulating in a Script

If you don’t want to accidentally override your functions, encapsulate them in a separate script and source that file in the main script. Here’s how:

  1. Create a script named “my_script.sh” and define a function there:
    my_function() {
    # Function code here
    }
  2. Now, source the “my-script” in the “main_script.sh” to use the “my_function” without worrying about being overridden:
    source my_script.sh
    my_function

Conclusion

Overriding commands allows users to customize the behavior of commands. After reading this article you will get to know the importance of overriding commands and how to do it. Here, I have demonstrated 3 methods including 2 cases to override commands in bash. Moreover, I have explained how to prevent a function from accidentally being overridden. Pick any method that better suits your needs. Good luck!

People Also Ask

How can I override Linux commands?

To overwrite Linux commands, use the Bash function and replace the name of the function with the name of the command, or create an alias for the command. You can also set an environment variable to perform this task. For example: to override the ls command with ls -lh, define a function named “ls” and then write command ls -lh inside the function. After that, when you call the “ls” function, it will run the “ls -lh” command instead of the ls command.

What are bash commands?

Bash commands are the shell commands that you can run inside the Bash shell. These commands allow users to manage files and directories, navigate through a system, and control various types of data.

What is overriding command?

Overriding commands is a mechanism for replacing the existing command with a new command. It can change the functionality of the default commands. Like, replacing the “ls” command with “ls -li” so that it will execute the ls -li whenever you write ls in the terminal.

How do I override a file in terminal?

To override the contents of the file in the terminal, you can use the redirection operator > along with the echo or cat command. Suppose, you want to override the output of the cat command to the existing contents of the “file.txt”. To do so, use cat > file.txt. Besides, if you want to override the text “welcome to Linuxsimply” directly into the “file.txt”, use echo "welcome to Linuxsimply" > file.txt.

How do you use override function?

To use override function, just redefine the override function with the same name as the original function. Here you go:

# Define the original function
original_function() {
echo "Original function"
}

# Call the original function
original_function

# Redefine the original function with a new implementation
original_function() {
echo "Overridden function"
}

# Call the overridden function
original_function

How to revert overriding Bash function?

To revert the overriding of the Bash functions, you can use “unset -f” followed by the function name. If you wish to revert the overriding of the pwd command, type unset -f pwd in the terminal.

Why overriding commands is useful?

Overriding commands is useful when you don’t want to write the long command repeatedly or you want to create a short name for the command. It also helps in creating custom commands. Overriding command saves users time, effort, and improves productivity and efficiency.

Related Articles


<< Go Back to Bash Functions | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment