Linux Shell Scripting Beginner Tutorials – Part II

In this second series, you will learn about script debugging, conditional statements and case statements.

Debugging shell script

Everything goes wrong at some point. You can debug the shell script for error like any other programming languages using two switches “-v” and “-x”. Just append the switched before the script name to debug the script.

Command line arguments:

Arguments are something which will follows the command. For example , echo $0 , here echo is the command and $0 Is an argument passed to the command. $0 , by default will return the name of the shell script. Create a script file with .sh extension and try out the following example.

save the file and pass any two strings with the script file.

Once you run your script with two arguments, you will get the names of two arguments and shell script name as output because $1 and $2 gets the arguments passed with the command.

Conditional Statements

You can use conditional statements like if, else in the script to make decisions. Let’s look at a simple example which uses conditional statement.

If ,then, else and elif Statements:

Sample script for conditional statements:

In the above code snippet, we get an user input from keyboard. The if statement checks if the input matches the “scriptcrunch” string. If the string is matched it will display the message from the “ then block” or else the “else” statement will be invoked and the message inside the else block will be displayed. “fi” closes the if code block. Note: When we deal with mathematical expressions, we use “–eq” instead of “=” in the if condition.

Working with loops

Shell script supports for and while loops.

Syntax for “for” loop

Syntax for while loop

Sample script for “for” loop:

In the above script, name stores the name you enter in the keyboard using read function. Times store the input value given by the user. In for loop we use times variable to print the name “n”times. ie the value given by the user.

Sample script for while loop:

case statements

You can use case statements in shell script. The case statement will execute the commands which match the value mentioned in the case statement. Save the following script in case.sh file and change the permissions to 755 to execute the script.

Related

How do I install latest ansible server on a Redhat or Centos 7 server? You can easily install the latest stable…

Read more

This guide will help in Jenkins installation using step by step instructions. It explains the different methods to…

Read more

I assume that you have lamp stack installed in your system. And if you have PHP version lower than 5.1, you have…

Read more
About

The Best Tutorials & Tips to Speedup Your DevOps Workflow.

Created by Bibin Wilson.