How to Use Alias With Parameters in Bash Scripting? [6 Examples]

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'
EXPLANATION

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.What is Alias in BashAs 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'
EXPLANATION

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

Creating an Alias in Command-LineAs 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'
EXPLANATION

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

Creating Alias with Multiple ArgumentsAs 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

Removing a Alias from the Current SessionAs 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'
EXPLANATION

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

Combining Multiple Commands in a Bash AliasAs 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
EXPLANATION
  • 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."
EXPLANATION

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
EXPLANATION
  • 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

Creating a Permanent Alias Using a Bash ScriptAs 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
EXPLANATION
  • 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
}
EXPLANATION

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. Bash Alias Accepting the Parameter in the .bashrc File➎ Now, to make the changes take effect, you can either restart your terminal or run the following command:

source ~/.bashrc
EXPLANATION

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

Bash Alias Accepting the Parameters in the .bashrc FileAs 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

How do I run an alias?
To run an alias in Bash, simply type the alias name followed by any necessary arguments in the terminal. Press Enter to execute the command or sequence associated with the alias.
What is the purpose of an alias in Bash?
The purpose of an alias in Bash is to create custom shortcuts for frequently used or complex commands, streamlining the command-line experience and enhancing productivity.
What are Bash parameters?
Bash parameters refer to the values or arguments supplied to a Bash script or function during execution. These inputs enable customization, data manipulation, and decisionmaking within the script or function, enhancing its versatility.
Can bash functions take in parameters?

Certainly, Bash functions can accept parameters, allowing you to pass values or arguments to the function for processing within its code block.

Related Articles


<< Go Back to Parameters in Bash Scripting | Bash Scripting Tutorial

5/5 - (9 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment