Argument to linux script

How can I pass a command line argument into a shell script?

I know that shell scripts just run commands as if they were executed in at the command prompt. I’d like to be able to run shell scripts as if they were functions. That is, taking an input value or string into the script. How do I approach doing this?

8 Answers 8

The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script , ./script , /home/user/bin/script or whatever. Any arguments appear as «$1» , «$2» , «$3» and so on. The count of arguments is in the shell variable «$#» .

Common ways of dealing with this involve shell commands getopts and shift . getopts is a lot like the C getopt() library function. shift moves the value of $2 to $1 , $3 to $2 , and so on; $# gets decremented. Code ends up looking at the value of «$1» , doing things using a case … esac to decide on an action, and then doing a shift to move $1 to the next argument. It only ever has to examine $1 , and maybe $# .

the C getopt() is an extremely established standard, but the getopt executable is not the same across distro/platform. I’m a now fully converted getopts user, as it is a POSIX standard. It works great with dash also, which is my preferred script shell

You can access passed arguments with $n where n is the argument number — 1, 2, 3, . . You pass the arguments just like you would with any other command.

$ cat myscript #!/bin/bash echo "First arg: $1" echo "Second arg: $2" $ ./myscript hello world First arg: hello Second arg: world 

I can not get the right result from yours. The following is mine: »’ #!/bin/bash echo ‘First arg:’ $1 echo ‘Second arg:’ $2 »’ The shell name is para_script.sh Then execute it: »’ ./para_script.sh hello world

On a bash script, I personally like to use the following script to set parameters:

#!/bin/bash helpFunction() < echo "" echo "Usage: $0 -a parameterA -b parameterB -c parameterC" echo -e "\t-a Description of what is parameterA" echo -e "\t-b Description of what is parameterB" echo -e "\t-c Description of what is parameterC" exit 1 # Exit script after printing help >while getopts "a:b:c:" opt do case "$opt" in a ) parameterA="$OPTARG" ;; b ) parameterB="$OPTARG" ;; c ) parameterC="$OPTARG" ;; ? ) helpFunction ;; # Print helpFunction in case parameter is non-existent esac done # Print helpFunction in case parameters are empty if [ -z "$parameterA" ] || [ -z "$parameterB" ] || [ -z "$parameterC" ] then echo "Some or all of the parameters are empty"; helpFunction fi # Begin script in case all parameters are correct echo "$parameterA" echo "$parameterB" echo "$parameterC" 

With this structure, we don’t rely on the order of the parameters, as we’re defining a key letter to each one of them. Also, the help function will be printed all the times that the parameters are defined wrongly. It’s very useful when we have a lot of scripts with different parameters to handle. It works as the following:

$ bash myscript -a "String A" -b "String B" -c "String C" String A String B String C $ bash myscript -a "String A" -c "String C" -b "String B" String A String B String C $ bash myscript -a "String A" -c "String C" -f "Non-existent parameter" myscript: illegal option -- f Usage: myscript -a parameterA -b parameterB -c parameterC -a Description of what is parameterA -b Description of what is parameterB -c Description of what is parameterC $ bash myscript -a "String A" -c "String C" Some or all of the parameters are empty Usage: myscript -a parameterA -b parameterB -c parameterC -a Description of what is parameterA -b Description of what is parameterB -c Description of what is parameterC 

Источник

Читайте также:  Linux what is npm

How to Use Command Line Arguments in a Bash Script

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

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:

echo "Username: $1"; echo "Age: $2"; echo "Full Name: $3";

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

sh userReg-positional-parameter.sh john 25 'John Smith'
Username : john Age: 25 Full Name: John Smith

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.

Читайте также:  Zip directory in linux command

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:

while getopts u:a:f: flag do case "$" in u) username=$;; a) age=$;; f) fullname=$;; esac done echo "Username: $username"; echo "Age: $age"; echo "Full Name: $fullname";

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

sh userReg-flags.sh -f 'John Smith' -a 25 -u john

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

Username : john Age: 25 Full Name: John Smith

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:

i=1; for user in "[email protected]" do echo "Username - $i: $user"; i=$((i + 1)); done
sh users-loop.sh john matt bill 'joe wicks' carol
Username - 1: john Username - 2: matt Username - 3: bill Username - 4: joe wicks Username - 5: carol

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.

Читайте также:  Drweb live cd для linux

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:

sh parityCheck.sh 13 18 27 35 44 52 61 79 93

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:

i=1; j=$#; while [ $i -le $j ] do echo "Username - $i: $1"; i=$((i + 1)); shift 1; done

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

sh users-shift-operator.sh john matt bill 'joe wicks' carol

The output will be the same as before:

Username - 1: john Username - 2: matt Username - 3: bill Username - 4: joe wicks Username - 5: carol

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 on GitHub.

Источник

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