How to Handle Command Line Arguments in a Bash Script

29/12/2020
In many cases, bash scripts require argument values to provide input options to the script. You can handle command line arguments in a bash script by two ways. One is by using argument variables and another is by using getopts function. How you can handle command line arguments is shown in this tutorial.

Using argument variables:

Argument variable starts from $0. The main script file name is stored in $0 which receives argument values from command line arguments. If two arguments are passed in command line then the argument values will be received in $1 and $2 variables sequentially.

Example -1: Sending three numeric values as arguments

Create a bash file and add the following code. The script will receive three argument values and store in $1, $2 and $3. It will count the total number of arguments, print argument values with loop and without loop. Lastly, print the sum of all argument values.

#!/bin/bash
 
# Counting total number of arguments
echo "Total number of arguments : $#"
 
# Reading argument values individually
echo "First argument value : $1"
echo "Second argument value : $2"
echo "Third argument value : $3"
 
# Reading argument values using loop
for argval in "[email protected]"
do
  echo -n "$argval  "
done
 
# Adding argument values
sum=$(($1+$2+$3))
 
# print the result
echo -e "nResult of sum = $sum"
 

Run the bash file with three numeric argument values.

$ bash cmdline1.sh 50 35 15

Example -2: Taking filename as argument

Create a bash file and add the following code to count the total number of characters of any file. Here, filename will be passed as command line argument.

#!/bin/bash
filename=$1
totalchar=`wc -c $filename`
echo "Total number of characters are $totalchar"

Run the bash script with the filename as single argument value and run another command to check the total number of characters of that file. Here, employee.txt file is used as argument value. Total number of characters of employee.txt file is 204.

$ bash cmdline2.sh employee.txt
$ wc -c employee.txt

Using getopts function:

If you want to store data in database or any file or create a report on particular format based on command line arguments values then getopts function is the best option to do the task. It is a built-in linux function. So, you can easily use this function in your script to read formatted data from command line.

Example -1: Reading arguments by getopts function

Create a bash file and add the following script to understand the use of getopts function. ‘getopts’ function is used with while loop to read command line argument options and argument values. Here, 4 options are used which are ‘i’, ‘n’, ‘m’ and ‘e’. case statement is used to match the particular option and store the argument value in a variable. Finally, print the values of the variable.

#!/bin/bash
while getopts ":i:n:m:e:" arg; do
  case $arg in
    i) ID=$OPTARG;;
    n) Name=$OPTARG;;
    m) Manufacturing_date=$OPTARG;;
    e) Expire_date=$OPTARG;;
  esac
done
echo -e "n$ID  $Name   $Manufacturing_date $Expire_daten"

Run the file with the following options and argument values. Here, p100 is the value of -i option, ‘Hot Cake’ is the value of -n option, ’01-01-2018′ is the value of -m option and ’06-01-2018′ is the value of -e option.

$ bash cmdline3.sh -i p001 -n ‘Hot Cake’ -m ’01-01-2018′ -e ’06-01-2018′

When you need to send simple values in a script then it is better to use argument variables. But if you want to send data in a formatted way then it is better to use getopts function to retrieve argument values. For more information watch the video!

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

bash date examples

Bash uses `date` command to display or change the current date and time value of the system. Date and time value can be...
29/12/2020

Squid Proxy Manager cài đặt và quản lý Proxy Squid tự động trên ubuntu

Các tính năng chính : ADDIPTOSERVER SHOWAVAILABLEPROXIES ADDUSER ASSIGNIPTOUSER SHOWSUSERSEXPIREDATE MODIFYUSERSEXPIRYDATE SHOWUSERSPROXYINFO DELETEIPFROMSERVER DELETEUSERPROXY DELETEUSER SHUTDOWNPROXY STARTPROXY EXPORTAVAILABLEPROXY EXPORTUSERSPROXY ADDBLACKLIST SHOWBLACKLIST DELETEBLACKLIST EXIT RANDOMPROXIES CHANGEIP-MULTIPLIER Cài...
20/10/2021

Bash lowercase and uppercase strings

String data are used for different purposes in any bash commands or programming script. Sometimes we need to change the...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Lý do tại sao bạn nên sử dụng proxy khi truy cập web đen
27/02/2023

Các lỗi thường gặp khi sử dụng proxy và cách khắc phục chúng.
27/02/2023

Tác động của việc sử dụng proxy đến tốc độ kết nối internet của bạn.
27/02/2023

Các tiện ích và công cụ để quản lý proxy.
27/02/2023

Các cách để kiểm tra tốc độ và độ ổn định của proxy.
27/02/2023