linux bash scripting
Linux

Linux bash scripting the awesome guide part3

So far you’ve seen how to write Linux bash scripts that interact with data, variables, and 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

 

Our main points are

Reading parameters

Testing parameters

Counting parameters

Grabbing all parameters

Shift command

Bash scripting options

Separating options from parameters

Processing options with values

Standardizing Options

Getting User Input

Reading password

Reading from a file

 

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

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

Command line parameters allow 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 those parameters in our bash script?

Reading parameters

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

  • $0 being the script’s name
  • $1 being the first parameter
  • $2 being the second parameter, and so on, up to $9 for the ninth parameter

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

if we run the script with the following parameters and look at the output

./myscript 5 10 15

If you need to enter more command line parameters, each parameter must be separated by a space

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 is not restricted to numbers it could be strings like this

 

./myscript Adam

And the result is as expected.

linux-bash-scripting-string-parameters

But 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 needs more than nine parameters, you must use braces around the variable number, such as ${10}.

Testing parameters

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

So Always check your parameters 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 provides a special variable for this purpose.

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

 

./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 used. Look at this trick

linux-bash-scripting-last-parameter

Grabbing all parameters

In some situations, you want to grab all the parameters provided.

The $* and $@ variables in Linux bash scripting provides you all of your 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 takes all the parameters supplied on the command line as a single word.

The $@ variable takes all the parameters as separate words in the same string, It allows you to iterate through them

This code shows the difference between 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

$* variable treated all the parameters as a single parameter, while the $@ variable treated each parameter separately. So you can use any one of those 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.

When you use the shift command, it moves each parameter variable one position to the left by default. So, the value for 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 great way to iterate through parameters

Here the script performs a while loop, checking the length of the first parameter’s value. When The first parameter’s length is zero, the loop ends. After testing the first parameter, the shift command is used 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 preceded by a dash that alters 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 appropriate commands are run in the case statement.

Separating options from parameters

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

This special character is the double dash (–). The shell uses the double dash to indicate the end of the options list. After seeing the double dash, your script can safely process the remaining command line parameters as parameters and not 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 script reaches the double dash, it stops processing options and assumes that any remaining parameters are command line parameters. I love Linux bash scripting.

Processing options with values

When you dig deep onto Linux bash scripting Sometimes you need options with additional parameter value like this

./myscript -a test1 -b -c test2

Your script must be able to detect when your command line option requires 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

In this example, the case statement defines three options that it processes.

The -b option also requires an additional parameter value. Because the parameter being processed is $1, you know that the additional parameter value is located in $2 (because all the parameters are shifted after they are processed). Just extract the parameter value from the $2 variable. Of course, because we used two parameter spots for this option, you also need to set the shift command to shift one additional position.

Well, that works well but there are limitations. For example, this doesn’t work if you try to combine multiple options in one parameter like this

./myscript abc

Surely it will give you abc is not an option

Fortunately, there’s another method for processing options that can help you in this situation

Standardizing Options

When you start your Linux bash scripting, it’s completely up to you to choose which letter options you select to use and how you select to use them.

However, a few letter options have achieved a somewhat 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 option meanings.

Using the same meaning for your options helps users interact with your script without having to worry about manuals.

Getting User Input

Providing command line options and parameters is 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 provides the read command just for this purpose.

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

Notice that the echo command that generated the prompt uses the –n option. This prevents the newline character at the end of the string, allowing the script user to enter data immediately after the string, instead of on 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 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 go on regardless of whether any data was entered, you can use the -t option to specify a timer. The -t option specifies 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 sorry message

linux-bash-scripting-timeout

Reading password

In Linux bash scripting Sometimes you don’t want that input to display on the screen like entering a password.

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

The data is displayed, but the read command sets the text color to the same as the background color.

linux-bash-scripting-hidden-input

Reading from a file

The read command reads a single line of text from the file on each call.

When no more lines are left in the file, the read command just stop.

Now if you want to get all file data you can pipe the result of cat command of the file to while command that contains read command (I know the cat command smells like noob but I want beginners and gurus got my point).

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 simple enough huh?

I hope you find this post interesting and I’m going to make more posts about Linux bash scripting

Thanks.