linux bash scripting
Linux

Linux bash scripting Part3 – Parameters and Options

So far you’ve seen how to write Linux bash scripts that interact with data, variables, files, and how to control the flow of the bash script. Today we will continue our series about Linux bash scripting.

I recommend you to review the previous posts if you want to know what we are talking about.

bash scripting part1

bash scripting part2

Today we will know how to retrieve input from the user and deal with that input, so our script becomes more interactive.

The common method of passing data to your shell script is to use command line parameters.

Command line parameters enable you to add data values to the command line when you execute the script.

$ ./myscript 10 20

This example passes two command line parameters (10 and 20) to the script. So how to read these parameters in our bash script?

Reading parameters

The bash shell assigns special variables called positional parameters, to all of the passed command line parameters:

  • $0 is the script’s name.
  • $1 is the first parameter.
  • $2 is the second parameter, up to the ninth parameter $9.

Here’s a simple example of how to use command line parameters in a shell script

Check the results of the following command:

./myscript 5 10 15

linux bash scripting parameters

Here is another example of how we can use two parameters and calculate the sum of them.

linux-bash-scripting-parameters

The parameters are not restricted to numbers, they could be strings like this:

./myscript Adam

And the result is as expected.

linux-bash-scripting-string-parameters

What if our parameter contains a space and we want to pass it as one value? I guess you know the answer from the previous posts. The answer is to use quotations.

If your script requires over nine parameters, you need to use braces around the variable number, such as ${10}.

Testing parameters

If the script runs without the parameters and your code expecting it, you’ll get an error message from your script.

So always check your parameters using if statement to make sure that they exist.

linux-bash-scripting-testing-parameters

Counting parameters

You can count how many parameters were entered on the command line. The bash shell gives us a special variable for this purpose.

The special $# variable contains the number of the passed command line parameters.

./myscript 1 2 3 4 5

linux--bash-scripting-parameters-count

How awesome is Linux bash scripting? This variable also provides a geeky way of getting the last parameter on the command line without having to know how many parameters were passed. Look at this trick:

linux-bash-scripting-last-parameter

Grabbing all parameters

In some cases, you need to get all the parameters provided.

The $* and $@ variables in Linux bash scripting provide you all of the passed parameters. Both of these variables include all the command line parameters within a single variable. So you don’t have to grab them by $# variable and iterate over them, just one step.

The $* variable holds all the parameters supplied on the command line as a single word.

The $@ variable takes all the parameters as separate words within the same string, it enables you to iterate over them.

This code shows how to use them:

linux-bash-scripting-grab-all-parameters

Both variables produce the same output, but if you want to know the difference look at the following example:

Now you see the difference.

linux-bash-scripting-parameters-count

The $* variable treated all the parameters as a single parameter, while the $@ variable treated each parameter separately. So you can use any one of these variables according to your needs.

Shift command

The shift command has some little risk in Linux bash scripting, it literally shifts the command line parameters in their relative positions.

The shift command moves every parameter variable one position to the left by default, so the value for the variable $3 is moved to $2, the value for variable $2 is moved to $1, and the value for variable $1 is discarded (note that the value for variable $0, the script name, remains unchanged).

This is another way to iterate over parameters:

Here, the script performs a while loop, checking the length of the first parameter’s value. When The length of the first parameter is zero, the loop stops. After examining the first parameter, the shift command is utilized to shift all the parameters one position.

linux-bash-scripting-shift-command

Careful when using shift command because when a parameter is shifted, its value is removed and cannot be recovered.

Bash scripting options

Options are single letters with a dash before them, they alter the behavior of a command.

$ ./myscript a b c d

linux-bash-scripting-options

The case statement checks each parameter for valid options. When one is found, the suitable commands will run.

Separating options from parameters

Often in Linux bash scripting, you’ll run into situations where you’ll need to use both options and parameters in a bash script. The standard way to do this is to separate them with a special character code that tells the script when the options are finished and when the parameters start.

This special character is the double dash (–) which is used to indicate the end of the options list. After the shell sees the double dash, the script can safely process the remaining command line inputs as parameters and not as options.

This bash script uses the break command to break out of the while loop when it encounters the double dash.

linux-bash-scripting-options-with-parameters

As you can see from the result, when the double dash is found, the bash will stop processing options and assumes that any remaining parameters are command line parameters.

Processing options with values

When you dig deep onto Linux bash scripting, sometimes you need options with additional parameter values like this:

./myscript -a test1 -b -c test2

Your script must be able to identify when your command line option has an additional parameter and be able to process it.

And if we run it with these options:

./myscript -a -b test1 -d

linux-bash-scripting-mix-options-with-parameters

Here we define three options.

The -b option has additional parameter value because the processed parameter is $1.

Just obtain the parameter value from the $2 variable. You also need to set the shift command to shift one additional position.

 

Standardizing Options

When you start your Linux bash scripting, it’s completely up to you to choose which letter is suitable for your option.

However, there are some letters that have a standard meaning in the Linux world.

And here is the list of the common options:

-a            Shows all objects

-c            Produces a count

-d            Specifies a directory

-e            Expands an object

-f             Specifies a file to read data from

-h            Displays a help message for the command

-i             Ignores text case

-l             Produces a long format version of the output

-n            Uses a non-interactive (batch) mode

-o            Specifies an output file to redirect all output to

-q            Runs in quiet mode

-r             Processes directories and files recursively

-s            Runs in silent mode

-v            Produces verbose output

-x            Excludes an object

-y            Answers yes to all questions

If you work with Linux, you’ll probably recognize most of these options meanings.

Using these letters as your options helps users to use your script without having to worry about manuals.

Getting User Input

Providing command line options and parameters are a great way to get data from your bash script users, but sometimes your script needs to be more interactive.

Sometimes you need data from the user while the bash scripting is running.

The bash shell uses the read command for this purpose.

The read command accepts input either from standard input (the keyboard) or from another file descriptor. After that, the read command places the data into a variable and here is an example:

Notice that the echo command that generates the prompt uses the -n option. This disables the newline character at the end of the string, this will allow you to enter data immediately after the string, instead of the next line.

linux-bash-scripting-read-input

You can specify multiple variables like this:

linux-bash-scripting-multi-input

If you don’t specify any variable for the read command the read command places any data it receives in the special environment variable REPLY.

linux-bash-scripting-reply-variable

If your bash script must complete running regardless of whether any data was entered or not, you can use the -t option to specify a timer. The -t option is used to specify the number of seconds for the read command to wait for input.

If you do not enter data for five seconds the script will execute the else clause and print a sorry message.

linux-bash-scripting-timeout

Reading password

In Linux bash scripting, sometimes you don’t want the user input to be displayed on the screen, like entering a password.

The -s option hides the data entered in the read command from being displayed on the screen.

The data is actually printed on the screen, but the read command sets the text color to the same as the background color.

linux-bash-scripting-hidden-input

Reading from a file

If you pass a file to the read command, the read command will read a single line from the file on each call.

If there are no more lines left in the file, the read command just stops.

Now, if you want to get all file data, you can pipe the result of the cat command to the while command that contains read command.

linux-bash-scripting-read-from-file

We just pass the file content to while loop and iterate over every line and print the line number and the content, and each time you increase the count by one.

I hope you find this post interesting. Keep coming back.

Thank you.