Arguments from command line linux

How to Use Command Line Arguments in a Bash Script

Last modified: January 30, 2021

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Introduction

We’ve previously examined how to pass command-line arguments to a bash script. In this tutorial, we’ll take a look at how we can use these arguments inside the bash script.

Further reading:

How to Pass Command Line Arguments to Bash Script

How to Use the cd Command in Bash Scripts

Reading Output of a Command Into an Array in Bash

2. Processing the Input

Let’s take a look at the different ways to process the arguments passed to a bash script inside the script.

2.1. Positional Parameters

Arguments passed to a script are processed in the same order in which they’re sent. The indexing of the arguments starts at one, and the first argument can be accessed inside the script using $1. Similarly, the second argument can be accessed using $2, and so on. The positional parameter refers to this representation of the arguments using their position.

Let’s take an example of the following script, userReg-positional-parameter.sh, which prints username, age, and full name in that order:

Now let’s run this script with the three input parameters:

The output will be:

2.2. Flags

Using flags is a common way of passing input to a script. When passing input to the script, there’s a flag (usually a single letter) starting with a hyphen (-) before each argument.

Let’s take a look at the userReg-flags.sh script, which takes three arguments: username (-u), age (-a), and full name (-f).

We’ll modify the earlier script to use flags instead of relying on positional parameters. The getopts function reads the flags in the input, and OPTARG refers to the corresponding values:

Let’s run this script with the same input as before, only this time, we’ll add flags to the input:

The output is the same as before, though we have shifted the positions of the username and full name arguments:

Here we’re using the getopts function to parse the flags provided as input, and the case block to assign the value specified to the corresponding variable.

2.3. Loop Construct

Positional parameters, while convenient in many cases, can’t be used when the input size is unknown. The use of a loop construct comes in handy in these situations.

The variable [email protected] is the array of all the input parameters. Using this variable within a for loop, we can iterate over the input and process all the arguments passed.

Let’s take an example of the script users-loop.sh, which prints all the usernames that have been passed as input:

Now let’s run the script:

And we’ll see our output:

In the above example, we’re iterating the user variable over the entire array of input parameters. This iteration starts at the first input argument, john, and runs until the last argument, carol, even though the size of the input is unknown.

2.4. Shift Operator

Shift operator in bash (syntactically shift n, where n is the number of positions to move) shifts the position of the command line arguments. The default value for n is one if not specified.

The shift operator causes the indexing of the input to start from the shifted position. In other words, when this operator is used on an array input, the positional parameter $1 changes to the argument reached by shifting n positions to the right from the current argument bound to positional parameter $1.

Consider an example script that determines whether the input is odd or even:

Читайте также:  Алфавит для маленьких для распечатки на принтере

From the above discussion on the positional parameter, we now know that $1 refers to the first argument, which is 13. Using the shift operator with input 1 (shift 1) causes the indexing to start from the second argument. That is, $1 now refers to the second argument (18). Similarly, calling shift 2 will then cause the indexing to start from the fourth argument (35).

Let’s again take a look at the example of users script discussed above. Instead of using the [email protected] variable and iterating over it, we’ll now use the shift operator. The $# variable returns the input size:

Let’s run the script with the same input as above:

The output will be the same as before:

In this example, we’re shifting the positional parameter in each iteration by one until we reach the end of the input. Therefore, $1 refers to the next element in the input each time.

3. Conclusion

In this article, we looked at how arguments passed to a bash script during runtime can be processed inside the script in different ways:

  • Positional parameters can be used when the input size is fixed and the order of the arguments in the input is known.
  • With flags, the order of the arguments in the input doesn’t matter.
  • Loop construct comes in handy when the input size is unknown.
  • Shift operator causes indexing to start from the argument at the shifted position.
  • The variable [email protected]returns the array of input parameters, and $# returns the size of the input array.

As always, the examples used in this article are available over on GitHub.

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Источник

How to Pass Command Line Arguments to Bash Script

In this tutorial, we will learn how to pass command line arguments to a bash shell script in Linux.

Command line arguments are the arguments specified at the command prompt with a command or script to be executed. The locations at the command prompt of the arguments as well as the location of the command, or the script itself, are stored in corresponding variables. These variables are special shell variables. Below picture will help you understand them.

Let’s create a shell script with name “arguments.sh”, it will show the command line arguments that were supplied and count number of arguments, value of first argument and Process ID (PID) of the Script.

Save and close the file.

Assign Executable permissions to the script using chmod command

Now execute the script with following command line arguments

In above script, we can also use ‘[email protected]’ in place of $* to get all the arguments. The key difference between these two variables is that ‘$*’ represent all the parameters in single string whereas ‘[email protected]’ represent arguments as a array or [email protected] expands to multiple arguments.

‘[email protected]’ is always preferred over ‘$*’, to understand their difference , let’s create following script,

Save & exit the file.

Execute the script and notice the difference

Shifting Command Line Arguments

The shift command is used to move command line arguments one position to the left. During this move, the first argument is lost. The above script would look like below after adding shift command to it.

Let’s re-run the script with following command line arguments,

Multiple shifts in a single attempt may be performed by furnishing the desired number of shifts to the shift command as an argument.

Note: Command line arguments are also known as positional parameters.

That’s all from this tutorial, I hope you have understood how to pass command line arguments to a bash script.

5 thoughts on “How to Pass Command Line Arguments to Bash Script”

Thank you so much

You missed [email protected], which is what a competent script would use (specifically “[email protected]”) to iterate over the input params, since either “$*” or $* would mangle parameters with shell metacharacters (i.e. would not work any time that user needs to quote the input parameters).

can you show us with example please.

If Command was called with eg. `Command “arg1” “arg two” “arg3″`, that’s three arguments.

Читайте также:  Linux apt install from local file

Saying `”$*”` in Bash means “a string with all the arguments joined by space. Saying `”[email protected]”`, means “an array with each argument”. (Kinda like spelling each argument but you don’t need to know how many there are.)

Say you wanted to use first argument for some logic and pass rest of them to another command, let’s say it’s mysql. Now you could say, `foo=$1; shift` — that would “consume” the first argument (`arg1`) to `$foo`. Fine. Now your argument array only contains `arg two` and `arg3`.

So now you want to pass these two arguments to, eg., “mysql”. But calling `mysql “$*”` just means calling mysql with *one* argument, that is, string `arg two arg3` which is something that basically never ever makes sense!.

Calling `mysql “[email protected]”` is almost always what you want.

Using non-quoted version of either syntax is even worse and pretty much useless: it just means that now the resulting value is subject to whole host of various bash expansions, word splitting (it’s `”argument” “two” “arg3”), etc. and may lead to unpredictable results based on eg. what is currently in the directory where the command is called.

Источник

How To Pass and Parse Linux Bash Script Arguments and Parameters

Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We’ll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script.

Passing arguments before running

We can pass parameters just after the name of the script while running the bash interpreter command. You can pass parameters or arguments to the file. Just the command for running the script normally by adding the value of the parameters directly to the script. Every parameter is a space-separated value to pass to the shell script.

The above command will just run the script without passing the parameters.

Whereas the command below will pass the arguments to the script.

Running bash script with passing parameters

The above screenshot displays the parameters passed to the script, how we’ll do that, which we’ll explain in the next section. But right now we can see we have passed in the parameters from outside of the script using bash environment variables. You can even use strings and other data types but beware of any whitespace. White space will make the variable a separate parameter. So, for strings especially, be careful to strictly surround them with quotation marks.

Detecting Command Line Arguments

Now, we’ll see how we access those parameters inside of the script. We’ll use the number of the parameters passed in the order i.e for the first parameters passed, we’ll parse(access) the parameter by using $1 as the variable. The first parameter is stored in the $1 variable. Furthermore, you can assign this variable to any other user-defined variable you like. For the nth parameter passed, you can use $n to access that particular parameter. Here, the variable name starts with 1 because the filename/ script name is the 0th parameter. If you have more than 9 parameters, make sure to use < >around the number as without the parenthesis, bash will only see $10 as $1 and exclude the 0, so use $ <10>and so on instead of simply $10.

The above script can access the parameters from the command line/ shell using the positional parameters, which are 1, 2, 3, and so on.

Accessing the arguments from the script.

As you can see, we have used <> to access the parameter variable numbers from 10 onwards. The script can be used for loops and while loops to iterate over the parameters, but we will discuss it in further sections.

Assign Provided Arguments To Bash Variable

We can also assign it to other custom variables to make the script more dynamic and mold it according to the needs. Though the above script when run will only print two parameters, surely you can access more parameters using the variable as the order of parameters in numbers. The script can access the positional variables from the command line and use them in the required places wherever needed within the script.

Assign Provided Arguments To Bash Variable

Читайте также:  Драйвера для принтера lexmark e342n

The above script accesses the positional parameters i.e $1 and $2 passed into the script and stores the user-defined variables to access them later and modify them accordingly. We can also access more parameters using iterative methods as we’ll see in the upcoming sections.

We also have the ability to check for any NULL or empty parameters passed using the -z or -n flags. From this, we can verify whether the parameters were passed or not.

Checking for positional parameters passed in or not.

With this script, we can detect whether any positional parameters were passed in or nothing was passed. The -z flag checks for any NULL or uninitialized variables in BASH. The -z flag returns true if the variable passed is NULL or uninitialized. Hence, we can make use of basic If-else statements to detect the parameters passed.

We can also use -n flag which returns true if no parameters are passed, so we have to make use of ! to reverse the condition.

Such as follows:

This script will also give the same output as well, but we are making use of -n flag instead of -z.

Reading Multiple Arguments with For or While loop

We can use “@” variable to access every parameter passed to the script via the command line. It is a special variable that holds the array of variables in BASH. In this case, we are using it alone, so it contains the array of positional parameters passed in. We can use it to iterate over the parameters passed using loops or while loop as well.

Using loops and @ variable to access the parameters as array elements.

We used a range-based for loop to iterate over till there are elements in the @ array. We simply iterate over the array and print the element. We can simply assign it, modify the values, and make the required changes to the parameters and arguments to achieve the desired outcome from the script.

We can also print the arguments using the while loop and the environmental variables of BASH.

Using while loop to iterate over the passed parameters.

We are using the variable ‘#‘ as it holds the number of parameters passed in. We initialize the number of parameters and take away one as we are going to use an array to iterate over it. So, as usual, the array’s index starts from 0. As this array is initialized from the last element or parameter passed, we need to decrement the counter until 0 to print every parameter in the order it is passed. We simply use the BASH_ARGV array to access the parameters and print its value. Also, at every iteration, we decrease the value of i- the iterator or counter by one using the arithmetic double braces. From this, we simply print every parameter passed to the script using a while loop as shown from the output screenshot.

Reading With Parameter Names

Using getopts to parse arguments and parameters

We can use the getopts program/ command to parse the arguments passed to the script in the command line/ terminal by using loops and switch-case statements.

Using getopts to parse arguments and parameters

Using getopts, we can assign the positional arguments/ parameters from the command line to the bash variables directly. This allows us to manage the parameters nicely and in a systematic way. In the above script, we have used two arguments to store the bash variables using the getopts syntax, while loops and switch-case statements.

Printing Values of All Arguments

We can print the arguments passed to the script by a simple powerful variable ‘@’ which stores all the parameters passed.

Printing Values of All Arguments

Accessing the number of Parameters passed

We can also use the variable ‘#’ to access the number of parameters passed from the command line. The # variable basically contains the number of parameters/ arguments which are passed into the script.

Accessing the number of Parameters passed

The following were the process and specification of passing and parsing the variables in the bash script. The logic of shifting and making modifications to the variables is in the hands of the user. This was just a demonstration of passing in and parsing down the arguments from the command line to the script to make them more dynamic.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector