How to Read in Command Line Arguments to Bash
In many cases, bash scripts crave argument values to provide input options to the script. You can handle command-line arguments in a bash script in two ways. One is past using argument variables, and another is by using the getopts function. How you tin handle control-line arguments is shown in this tutorial.
Using argument variables:
The argument variable starts from $0. The main script file proper name is stored in $0, which receives statement values from command line arguments. If 2 arguments are passed in the control-line, then sequentially, the statement values volition be received in $1 and $2 variables.
Example -1: Sending three numeric values in the control line arguments
Create a bash file with the post-obit script. The script will receive iii-argument values and store them in $i, $two, and $3 variables. It will count the total number of arguments and print statement values using a loop without a loop. The sum of all statement values will exist printed afterward.
#!/bin/bash
# Counting total number of arguments
echo "Total number of arguments: $#"
# Reading argument values individually
repeat "First argument value : $1"
echo "2d argument value : $2"
repeat "Third argument value : $3"
# Reading argument values using loop
for argval in "[e-mail protected]"
do
repeat -north "$argval "
done
# Calculation argument values
sum=$( ( $1+$two+$3 ) )
# print the result
echo -e "\northwardEvent of sum = $sum"
The following output will appear subsequently executing the script file with three numeric argument values, 50, 35, and 15.
$ bash cmdline1.sh 50 35 15
Example -2: Taking filename as an statement
Create a bash file with the following script to count the total number of characters of any file. Hither, the filename will be passed equally a command-line statement.
#!/bin/bash
filename=$ane
totalchar=` wc -c $filename `
echo "Total number of characters are $totalchar"
Run the bash script with the filename every bit a single statement value and run some other command to check that file's total number of characters. Hither, the weekday.txt file is used as an argument value. The full number of characters in the weekday.txt file is 57.
$ bash cmdline2.sh weekday.txt
$ wc -c weekday.txt
Using getopts function:
If you want to store information in the database or any file or create a report in a particular format based on command line arguments values, then the getopts function is the best option to practice the task. It is a built-in Linux function. So, you can hands utilize this function in your script to read formatted data from the control line.
Example -3: Reading arguments past getopts function
Create a bash file with the following script to understand the utilise of the getopts function. 'getopts' function is used with a while loop to read command-line statement options and argument values. Here, 4 options are used which are 'i', 'n', '1000' and 'east'. the case argument is used to match the detail choice and store the argument value in a variable. Finally, print the values of the variable.
#!/bin/fustigate
while getopts ":i:n:m:e:" arg; do
case $arg in
i) ID=$OPTARG ;;
n) Proper noun=$OPTARG ;;
m) Manufacturing_date=$OPTARG ;;
east) Expire_date=$OPTARG ;;
esac
done
repeat -due east "\n $ID $Proper noun $Manufacturing_date $Expire_date \due north"
Run the file with the following options and argument values. Here, p100 is the value of -i selection, 'Hot Cake' is the value of -north option, '01-01-2021' is the value of -m option and '06-01-2021' is the value of -due east option.
$ bash cmdline3.sh -i p001 -due north 'Hot Cake' -yard '01-01-2021' -e '06-01-2021'
When you need to ship simple values in a script, and then information technology is amend to apply argument variables. But if you lot want to send information in a formatted way, information technology is amend to employ the getopts function to retrieve argument values. The uses of both argument variables and getopts options have shown in the side by side example.
Instance-4: Reading normal arguments and arguments with getopts options
The ways to read command-line arguments using argument variables and getopts options take been shown separately in previous examples of this tutorial. But these two ways tin can exist used in a single script to read command-line argument values. Create a bash script with the post-obit code to read the command line argument values passed by getopts options and argument parameters. Here, three getopts options take been used to read the command line's hostname, username, and password. Next, shift command has been used to remove all getopts options from the control for reading the command line values using argument variables. This script will read and impress a maximum of 3 values of the argument variables. If no argument value without option volition be given after executing the lawmaking, and so a bulletin will be printed; otherwise, the values of the statement variable will be printed.
#!/bin/bash
# Reading arguments with getopts options
while getopts 'h:u:p:' OPTION; practise
case "$Option" in
h)
# Impress hostname
echo "The host name is $OPTARG" ;;
u)
# Impress username
echo "The username is $OPTARG" ;;
p)
# Print password
repeat "The password is $OPTARG" ;;
* )
# Impress helping message for providing wrong options
echo "Usage: $0 [-h value] [-u value] [-p value]" >& 2
# Terminate from the script
exit 1 ;;
esac
done
# Remove all options passed by getopts options
shift "$(($OPTIND -i))"
# Reading kickoff normal arguments
if [ ! -z $1 ]; then
echo "The showtime tabular array name is $1"
else
repeat "No normal argument is given."
exit 1
fi
# Reading 2d normal arguments
if [ ! -z $2 ]; then
echo "The second tabular array name is $2"
fi
# Reading third normal arguments
if [ ! -z $3 ]; and then
echo "The 3rd table name is $3"
fi
The following output will appear if the incorrect selection is given at the time of executing the code. Here, option -a does not exist in the script.
The following output will appear if the valid options with the values are given in the command line at the time of executing the lawmaking.
The following output will appear if the valid options and normal argument values are used in the command line at the fourth dimension of executing the code. Here, the normal arguments are customer and employee.
Using '[email protected]' for reading command-line arguments:
The command-line arguments tin exist read without using argument variables or getopts options. Using '[email protected]' with the first bracket is some other manner to read all command-line statement values.
Case-5: Reading command line argument values without variable
Create a bash file with the following script to read the statement values without whatsoever argument variable and calculate the sum of three control line argument values. "[email protected]" has been used with the first brackets here to read all statement values into an array. Adjacent, the sum of the outset three assortment values will be printed.
#!/bin/bash
# Read all arguments values
argvals=( "[email protected]" )
# Check the total number of arguments
if [ $# -gt ii ]
then
# Calculate the sum of three command line arguments
sum=$( ( ${argvals[0]}+${argvals[1]}+${argvals[ii]} ) )
echo "The sum of 3 command line arguments is $sum"
fi
The following output will appear after executing the above script for the argument values 12, xx, and 90. The sum of these numbers is 122.
Decision:
The ways to provide command-line statement values without any option and with options have shown here. The way to read control-line argument values without using variables has shown here as well. I hope this tutorial will help the readers to use control-line argument values properly in their bash script.
How to Read in Command Line Arguments to Bash
Source: https://linuxhint.com/command_line_arguments_bash_script/