In Bash scripting, the use of aliases with parameters enables the creation of custom shortcuts for frequently executed commands or sequences of commands while allowing for dynamic inputs. These aliases, often defined as functions, can accept arguments and parameters, making scripts more flexible and versatile. In this article, I am going to discuss 6 different examples of using alias with parameters in bash scripting. So let’s start.
Key Takeaways
- Getting familiarise with alias in bash scripting.
- Learning to set a permanent alias by modifying the .bashrc file.
Free Downloads
What is Alias in Bash?
In a Bash, an alias refers to a custom shorthand for a command or sequence of commands. The general syntax of an alias in Bash is as follows:
alias alias_name='command_to_run'
alias_name: is the name you want to assign to the alias.
command_to_run: is the command or sequence of commands you want the alias to represent. Use single quotes to enclose the command.
For Example, you want to create a folder named LinuxSimply in your current directory. The conventional way to do this task is using the following command.
mkdir -p LinuxSimply
However, you can put mkdir -p into an alias to make your command line short.As the image shows above, I put the mkdir -p into dir using the alias command. Then I create the LinuxSimply folder using the dir alias. This also allows you to create multiple folders efficiently as you do not need to call mkdir -p each time.
However, aliases are not typically used within Bash scripts but are more commonly utilized in interactive command-line environments to simplify and customize command usage.
6 Practical Examples of Using Alias With Parameters in Bash
As mentioned previously, alias with parameters in Bash scripting offers a versatile way to create custom shortcuts for frequently performed tasks. In this context, I’ll explore a few practical examples where alias functions accept arguments, allowing you to streamline and automate various tasks in your Bash.
For more convenient understanding in the first few examples, I’ll show you aliasing commands in the terminal. Then I will also explore how you can create a permanent alias with a bash script by modifying the .bashrc file.
Example 01: Creating an Alias With Parameters in Command-Line
Creating an alias with parameters allows you to create custom and reusable shortcut keys to ease your task. In the first example, you will get an overall idea of how to create a bash alias with one parameter in Linux. This alias simplifies the process of creating and navigating to a new directory with a single command. Let’s check this out.
Steps to Follow >
➊ Open the Ubuntu terminal using CTRL + ALT + T shortcut key.
➋ Write the following command in the command line.
alias dir='dir() { mkdir -p -- "$1" && cd -P -- "$1"; }; dir'
The alias dir is defined as a Bash function that takes one argument, which is used as a directory name. When invoked with an argument, dir creates a new directory with the given name using mkdir -p, ensuring parent directories are created if needed. It then changes the current directory to the newly created one using cd -P.
➌ Now use the pwd command to see the current path of your directory.
pwd
➍ Insert the command given below to create a new folder named newdir and move to the newly created folder subsequently.
dir newdir
➎ Now call the following command to see the current path of your folder.
pwd
As the image shows above, a newly created folder named newdir has been successfully created.
Example 02: Creating Bash Alias With Multiple Arguments
Following the previous example, you can incorporate multiple arguments within a single alias to make your work more efficient. Here is an example that provides a convenient way to pass and display values in the terminal.
Steps to Follow >
➊ Open the Ubuntu terminal using CTRL + ALT + T shortcut key.
➋ Write the following command in your command line.
alias myalias='myfunction() { echo "Argument 1: $1"; echo "Argument 2: $2"; }; myfunction'
The alias myalias is defined as a Bash function that takes two arguments and echoes them with descriptive labels. When invoked with two arguments, myalias will display the first argument as Argument 1 and the second argument as Argument 2.
➌ Now call the alias name myalias along with two positional parameters to execute it.
myalias Hello LinuxSimply
As the image suggests, the alias myalias invokes two arguments Hello and LinuxSimply, and successfully returns Argument 1: Hello and Argument 2: LinuxSimply.
Example 03: Removing a Bash Alias From the Current Session
You can eliminate the previously created alias from your Bash session by utilizing the unalias command. The structure of the unalias command is relatively simple.
unalias <alias_name>
Here are the detailed steps on how you can remove the alias from the current session.
Steps to Follow >
➊ Open the Ubuntu terminal using CTRL + ALT + T shortcut key.
➋ Write the following command in your command line to remove the myalias.
unalias myalias
➌ Run again the myalias alias by using the following command to make sure the removal process was done successfully.
myalias Hello LinuxSimply
As the image depicts, the command line shows “Command myalias not found”, reinforcing the idea of successful revocation of the bash alias.
Example 04: Combining Multiple Commands in a Bash Alias
To combine multiple commands in a Bash alias, you can use the && syntax and include the commands you want to run. For better understanding here is a syntax to avail the trick.
alias myalias='command1 && command2 && command3'
In this syntax: alias myalias starts the definition of the alias named myalias and command1 && command2 && command3 combines multiple commands using && syntax. However, each command will run only if the previous command succeeds (returns a zero exit status).
Here’s an example of how to create a Bash alias that combines multiple commands.
Steps to Follow >
➊ Open the Ubuntu terminal using CTRL + ALT + T shortcut key.
➋ Write the following command in the command line.
alias myalias='echo "Hello, World!" && ls -l && date'
The alias myalias is defined to execute a series of commands when invoked. It first uses the echo command to print the message “Hello, World!” to the terminal. Then, it runs the ls -l command, which lists the files in the current directory in a detailed format, showing file permissions, ownership, size, and modification timestamps. Finally, it uses the date command to display the current date and time.
➌ Call the myalias to execute all three commands simultaneously.
myalias
As the image suggests above, the alias myalias successfully displays all the output as specified.
Example 05: Creating a Permanent Alias With Parameters Using a Bash Script
To create a permanent alias using a Bash script, you can add the alias definition to your Bash configuration file, such as ~/.bashrc or ~/.bash_profile. In this section of the article, I am going to set a permanent alias by modifying ~/.bashrc file using a bash script. Here’s a step-by-step guide to do it:
Steps to Follow >
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file in Nano:
nano addtext.sh
- nano: Opens a file in the Nano text editor.
- addtext.sh: Name of the file.
❸ Copy the script mentioned below:
#!/bin/bash
# alias command to add to .bashrc
text_to_add=$1
# Append the command line to .bashrc
echo "\"$text_to_add\"" >> ~/.bashrc
# Reload .bashrc to apply changes
source ~/.bashrc
echo "Alias added to .bashrc and .bashrc reloaded."
This Bash script takes a command as an argument (text_to_add) and appends it as a line to the .bashrc file within double quotes. It then reloads the .bashrc file using the source command to apply the changes immediately. Finally, it prints a message indicating that the alias or command has been added to .bashrc and the file has been reloaded, ensuring the added command is available in the current and future terminal sessions.
❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.
❺ Use the following command to make the file executable:
chmod u+x addtext.sh
- chmod: Changes the permissions of files and directories.
- u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
- addtext.sh: File name.
❻ Run the script by the following command to set the bash alias in the .bashrc file permanently.
./addtext.sh "alias md='mkdir -p'"
➐ Lastly, use the following command to create a folder in the command line using the bash alias.
md LinuxSimply
As the image shows above, I have created a new folder named LinuxSimply using the permanent bash alias in the command line.
Example 06: Bash Alias Accepting the Parameters in the “.bashrc” File
To create a Bash alias that accepts parameters and define it in your .bashrc file, you can follow these steps:
Step to Follow >
➊ Open the Ubuntu terminal using CTRL + ALT + T shortcut key.
➋ Write the following command in your command line to open the .bashrc file.
nano .bashrc
- nano: Opens a file in the Nano text editor.
- .bashrc: Name of the file.
➌ Now scroll down to the last and write the following code in the .bashrc file
move_up() {
local steps="$1" path=""
[[ ! "$steps" =~ ^[0-9]+$ || "$steps" -lt 0 ]] && { echo "Invalid number of steps: $steps"; return 1; }
for ((i = 0; i < steps; i++)); do path="../$path"; done
cd "$path" || return 1
}
The Bash function move_up() takes a parameter where steps represent the number of directory levels to move up. It first validates that steps is a non-negative integer, and if not, it returns an error message. Then, it constructs a relative path by adding ../ to path for each iteration of a loop, effectively moving up the directory structure. Finally, it attempts to change the current directory to the calculated path, returning an error if unsuccessful, allowing for efficient navigation of directories in a script.
❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.➎ Now, to make the changes take effect, you can either restart your terminal or run the following command:
source ~/.bashrc
The command source ~/.bashrc is used to execute the commands and configurations stored in the .bashrc file within the user’s home directory. When this command is run, it reads the contents of the .bashrc file and executes any shell customizations or environment variable settings defined within it.
➏ Now execute the following command to see the path of the current directory.
pwd
➐ Then write the following command and execute it to move 2 steps forward from your current path.
move_up 2
➑ Execute the following command one more time to check whether you move 2 steps forward or not.
pwd
As you can see from the above image, the directory has been changed upon execution of the newly created bash alias.
Conclusion
In conclusion, using aliases with parameters in Bash scripting can empower you to create efficient and adaptable tools that simplify complex tasks and enhance the scripting experience. By incorporating dynamic inputs and custom shortcuts, these aliases improve code readability, maintainability, and overall script performance. In this article, I have discussed 6 different examples related to the topic. However, if you have any questions or queries related to this, feel free to comment below.
People Also Ask
Related Articles
- How to Pass All Parameters in Bash Scripts? [6 Cases]
- Parsing Parameters in Bash Scripts [5 Examples]
- 4 Methods to Pass Named Parameters in a Bash Script
- What is $0 in Bash Script? [4 Practical Examples]
- Difference Between $$ Vs $ in Bash Scripting [With Examples]
- How to Use Bash Function with Parameters? [6 Examples]
<< Go Back to Parameters in Bash Scripting | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners