Linux all command line arguments

Command Line Arguments in Linux

The command-line arguments in Linux are the parameters that the user provides via the terminal to the script, which uses them in the shell script. It points to the memory position of the command and its parameters that take the user input. It passes it to the shell script for execution to perform the specific task according to user input.

This article will explain the uses of command-line arguments in Linux with examples of the following topics:

  • How to Use Command Line Arguments in Linux?
  • Show Script Name
  • Pass Command Line Arguments From Terminal to Bash Script
  • Get Arguments Passed to Script
  • Find the Total Arguments Passed to Script
  • Get the Exit Code
  • Get Process ID
  • Use Command Line Arguments in For Loop

How to Use Command Line Arguments in Linux?

Bash scripts receive command line arguments from the terminal. Several command line arguments are built-in, which take the user input to perform a specific function. The pre-defined command line arguments in Linux are:

$0 It shows the script’s name.
$1 It shows the first command line argument.
$2 It takes the second argument from the terminal.
$# A script’s total number of arguments is displayed with this option.
[email protected] $* Both options provide the list of arguments given to the bash script.
$? It displays the exit code for the execution of the script.
$$ It shows the process ID (PID) for the script.

Note: This article will use the bash script named “arguments.sh”.

The command line arguments are utilized in Linux in the following ways.

Example 1: Show Script Name

The command line arguments are very useful while automating the tasks using the bash scripts. The command line argument predefined to get the script name is “$0”. To below shell script is used to print the text with echo command and script name:

#!/bin/bash echo "Welcome! To itslinuxfoss" echo "The script name is: $0"

Let’s explain the bash script line-by-line:

  • #!/bin/bash: Runs the script using bash.
  • echo: Display the text.
  • $0: Shows the script name.

Execute the bash script using this command:

The output shows that the script name is displayed using the command line arguments “$0”, and this method is very useful while using the conditional loops depending on the script name.

Example 2: Pass Command Line Arguments From Terminal to Bash Script

The command line arguments are given to the script via the terminal to make it interactive. The script can take the arguments using the “$ ”. The below script takes 3 arguments ($1, $2, $3) from the user via the terminal and displays the output:

#!/bin/bash echo "Welcome! To itslinuxfoss" echo "Your name is: $1" echo "Your age is: $2" echo "Your profession is: $3"

Execute the bash script using this command:

Читайте также:  Astra linux горячие клавиши fly

Three arguments, TestName, 22, and Content-Writer, are passed by the user in the script.

Example 3: Get Arguments Passed to Script

The list of arguments passed by the user can be listed using the “[email protected]” and “$*”. The below script takes two command line arguments from the user and lists the arguments:

Execute the bash script using this command:

The user passed two arguments, NewName and USA, that are listed by the script using [email protected].

Example 4: Find Total Arguments Passed to Script

When you need to find how many arguments are passed by the user, utilize the “$#” argument as shown below:

#!/bin/bash echo "Your favorite fruit: $1" echo "Your favorite color: $2" echo "Number of arguments passed are: $#"

Execute the bash script using this command:

The user passed two arguments, Mango and Black, which the script displays the number of arguments as 2.

Example 5: Get the Exit Code

The exit code can be found using the bash script that shows the status of the execution. The exit code depends on the state of execution like exit code is 0 for successful execution, while the 1-255 exit codes are for errors. For example, the below code displays the “Hello” text using the echo command and shows the script status with “$?”:

#!/bin/bash echo "Hello!" echo "The script exit code is: $?"

Execute the bash script using this command:

The script shows the exit code is 0, which means the execution is successful.

Example 6: Get Process ID

The bash script can be used to find the process ID PID with the command line argument. The “$$” shows the process ID of the script as shown below:

#!/bin/bash echo "Hello!" echo "The process ID of the script is: $$"

Execute the bash script using this command:

The output shows that the PID of the script is “3197” using the bash script.

Example 7: Using Command Line Arguments in For Loop

The command line arguments are commonly used in loops to automate the process. For example, the below script will display the number of arguments and their value given by the user with the for loop:

#!/bin/bash i=1; for fruit in "[email protected]" do echo "User - $i: $fruit"; i=$((i + 1)); done

Run the bash script using this command:

The user gives 3 arguments, Mango, Apple, and Banana which are displayed one by one with the for loop.

Conclusion

The command line arguments allow the users to pass the input from the terminal to the bash script, which makes the bash script interactive. The command line arguments can be used to automate the processes using the predefined arguments that are explained with examples in this guide.

Источник

Command Line Arguments

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 in two ways. One is by using argument variables, and another is by using the getopts function. How you can handle command-line arguments is shown in this tutorial.

Using argument variables:

The 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 the command-line, then sequentially, the argument values will be received in $1 and $2 variables.

Читайте также:  Linux увеличить swap файл

Example -1: Sending three numeric values in the command line arguments

Create a bash file with the following script. The script will receive three-argument values and store them in $1, $2, and $3 variables. It will count the total number of arguments and print argument values using a loop without a loop. The sum of all argument values will be printed later.

#!/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 «$@»
do
echo -n » $argval »
done

# Adding argument values
sum =$ ( ( $1 + $2 + $3 ) )

# print the result
echo -e » \n Result of sum = $sum «

The following output will appear after executing the script file with three numeric argument values, 50, 35, and 15.

Example -2: Taking filename as an argument

Create a bash file with the following script to count the total number of characters of any file. Here, the filename will be passed as a 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 a single argument value and run another command to check that file’s total number of characters. Here, the weekday.txt file is used as an argument value. The total number of characters in the weekday.txt file is 57.

Using getopts function:

If you want to store data 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 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 the command line.

Example -3: Reading arguments by getopts function

Create a bash file with the following script to understand the use of the getopts function. ‘getopts’ function is used with a while loop to read command-line argument options and argument values. Here, 4 options are used which are ‘i’, ‘n’, ‘m’ and ‘e’. the 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_date \n «

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-2021‘ is the value of -m option and ‘06-01-2021‘ is the value of -e option.

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, it is better to use the getopts function to retrieve argument values. The uses of both argument variables and getopts options have shown in the next example.

Example-4: Reading normal arguments and arguments with getopts options

The ways to read command-line arguments using argument variables and getopts options have been shown separately in previous examples of this tutorial. But these two ways can be used in a single script to read command-line argument values. Create a bash script with the following code to read the command line argument values passed by getopts options and argument parameters. Here, three getopts options have 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 command for reading the command line values using argument variables. This script will read and print a maximum of three values of the argument variables. If no argument value without option will be given after executing the code, then a message will be printed; otherwise, the values of the argument variable will be printed.

Читайте также:  Дамп оперативной памяти linux

# Reading arguments with getopts options
while getopts ‘h:u:p:’ OPTION; do
case » $OPTION » in
h )
# Print hostname
echo «The host name is $OPTARG » ;;
u )
# Print username
echo «The username is $OPTARG » ;;
p )
# Print password
echo «The password is $OPTARG » ;;
* )
# Print 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 -1) )»

# Reading first normal arguments
if [ ! -z $1 ] ; then
echo «The first table name is $1»
else
echo «No normal argument is given.»
exit 1
fi

# Reading second normal arguments
if [ ! -z $2 ] ; then
echo «The second table name is $2»
fi

# Reading third normal arguments
if [ ! -z $3 ] ; then
echo «The third table name is $3»
fi

The following output will appear if the wrong option 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 code.

The following output will appear if the valid options and normal argument values are used in the command line at the time of executing the code. Here, the normal arguments are customer and employee.

Using ‘$@’ for reading command-line arguments:

The command-line arguments can be read without using argument variables or getopts options. Using ‘$@‘ with the first bracket is another way to read all command-line argument values.

Example-5: Reading command line argument values without variable

Create a bash file with the following script to read the argument values without any argument variable and calculate the sum of three command line argument values. “$@” has been used with the first brackets here to read all argument values into an array. Next, the sum of the first three array values will be printed.

#!/bin/bash
# Read all arguments values
argvals = ( «$@» )
# Check the total number of arguments
if [ $# -gt 2 ]
then
# Calculate the sum of three command line arguments
sum =$ ( ( $ + $ + $ ) )
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, 20, and 90. The sum of these numbers is 122.

Conclusion:

The ways to provide command-line argument values without any option and with options have shown here. The way to read command-line argument values without using variables has shown here also. I hope this tutorial will help the readers to use command-line argument values properly in their bash script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью
Adblock
detector