How to Set Default Argument in Bash [2 Methods]

In Bash, one can set default values for command line arguments. If a default value is set for an argument, Bash expands to that default value whenever the argument is unset or null. Setting default arguments prevents unexpected halting of a Bash script. In this article, I will show how to set default values for arguments and a few use cases of default arguments.

What are Default Arguments in Bash?

Default arguments or default parameters are values assigned to arguments that are used when the user does not provide those arguments. Essentially, they offer a predetermined value for arguments when the user doesn’t supply one. The syntax for setting default values to a parameter is ${parameter:-default_value}, where “parameter” represents the argument and “default_value” signifies the value assigned if the argument is unset or null.

2 Ways to Set Default Values to Arguments in Bash

There are a couple of ways to set the default argument in Bash. All of them inherently use the parameter expansion technique. Go through the detailed process below to set a default argument:

1. Using Parameter Expansion

Parameter expansion in Bash is used for manipulating variables, including setting default values to positional parameters or arguments. To assign a default argument use the syntax ${parameter:-default_value}. Here is an example:

#!/bin/bash

var="${1:-User}"
echo "Hello, $var"
EXPLANATION

This Bash script sets up a variable named var, assigning it the value of the first command-line argument ($1). If no argument is provided, it defaults to “User”. Then, it echoes a message using the value of var, saying “Hello, $var”.

Setting default argument in BashRunning the script with no command-line argument prints “Hello, User”. It utilizes the default value “User” to print the text. On the contrary, when “Anita” is provided as the first argument, it suppresses the default value of the first argument to print “Hello, Anita”

2. Using If Statement

The if statement can be used to check if an argument is provided. After checking the existence of an argument one can set a default value if necessary. Here’s how it works:

#!/bin/bash

if [ -z "$1" ]; then
  set -- "${1:-GoodBye}"
fi

# Echo the first argument
echo "First Argument: $1"
EXPLANATION

The script checks if the first command-line argument is empty using the -z operator. If $1 is indeed empty, it utilizes parameter expansion ${1:-Good Bye} to set the default value “Good Bye” for the first argument. The set -- command then assigns this default value to $1. Finally, it echoes the value of the first argument.

Setting default argument using with if statement in BashOnce executed with the argument “Hi” the script displays the argument. However, when no argument is provided the script prints the default value of the first argument which is “GoodBye”.

Default Values of Command Line Arguments in Bash Script

Setting default values for command line arguments is crucial to prevent a Bash script from halting abruptly. For instance, consider the scenario of adding two numbers: if users provide both numbers, the script should compute their sum. However, if no or only one argument is provided, default values should be used instead of throwing an error. See the script below for clarification:

#!/bin/bash

arg1="${1:-0}"
arg2="${2:-0}"

# Echo the arguments
echo "Sum of numbers: $(($arg1+$arg2))"
EXPLANATION

The program utilizes parameter expansion ${1:-0} and ${2:-0} to set default values of 0 for the first and second arguments respectively, in case they are unset or empty. It then calculates the sum of the arguments using arithmetic expansion, $(($arg1+$arg2)) and prints the result.

Default argument in Bash scriptWhen executed with arguments 10 and 10, the program calculates the summation of the arguments. But without providing any argument the program prints that the summation is 0. Because the default values of the first and second arguments are 0.

Default Value of an Argument in a Bash Function

Default arguments are particularly useful in Bash functions. For instance, when checking the disk usage of a specific file or directory, users may need to provide the file or directory as an argument of a reusable function. However, setting the current directory as the default argument allows the function to use it if no argument is provided. An example illustrating this is provided below:

#!/bin/bash

du1() {
  local files="${1:-.}"
  du -hsc "$files"
}
du1
EXPLANATION

This Bash script defines a function du1() that calculates the disk usage of specified files or directories. It utilizes parameter expansion ${1:-.} to set the default value of the variable files to the current directory. Here, dot (.) represents the current directory.

If no argument is provided when calling the function, it uses the du command with the -hsc options to display the disk usage of the current directory. On the other hand, if any file or directory is provided as an argument the function displays the disk usage of that file or directory.

Default argument in Bash functionThe function is called without any argument in the above script. As a result, it prints the disk usage of the current directory which is 359M.

1 Practice Problem for Setting Default Arguments in Bash

Write a Bash script that converts bits to bytes or vice versa. It should take two arguments: a number and “b” for bits or “B” for Bytes. If the unit is provided, it should default to bits.

Conclusion

To sum up, setting default values for arguments in a Bash script is fairly simple. One can easily set default values for arguments using parameter expansion. Making an argument optional by setting default values enables a script to perform its go-to task. Moreover, it ensures the script runs even if the user forgets to provide the argument. I believe that from now on, you can easily set default arguments in a Bash script.

People Also Ask

How can I set a default argument in bash?

In Bash, you can set a default argument using ${parameter:-default} syntax. If the parameter is unset or null, it will use the default value; otherwise, it will use the given value of the parameter.

Why should I set a default value for a bash argument?

You should set a default value for a Bash argument to guard against unexpected behavior of a script. If you don’t provide a value, the script can rely on the default value to proceed with its operation. This ensures that your script doesn’t halt unexpectedly due to missing arguments.

How to override a bash argument with a new value?

To override a bash argument within a bash script, you can use the ${parameter:+new_value} syntax. This syntax allows you to replace the old value of the parameter with the new_value. However, If parameter is null or unset, nothing is substituted and parameter remains empty.

What is the purpose of setting an argument default to empty in bash?

Setting an argument default to empty in bash ensures predictable behavior, especially when handling cases where an argument doesn’t exist. While bash typically expands an unset argument to an empty string, in set -u mode, the shell throws a runtime error if the argument is unset. Unset means the variable has not been defined or it does not exist, whereas null or empty means the variable has a value, and this value is an empty string.

Related Articles


<< Go Back to Argument in Bash Script | Bash Functions | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment