Shell Programming in Linux

FREE Online Courses: Elevate Your Skills, Zero Cost Attached - Enroll Now!

In this article, you will learn all there is to shell programming in Linux-based operating systems. We will start right from the basics like what is a kernel, what is the command line, and what are graphical shells, and only then jump into the topic of shell programming.

We will understand what shell scripting is, why we use it, and its advantages and disadvantages of it. We will then dive headfirst into the practical part of shell programming where we will discuss various aspects of it like variables, expressions, if-else statements, while loop, for-loop, and so many more.

What is a shell?

Technically speaking in UNIX language, it is an interface between the user and operating system service. A shell provides users with an interface that not only accepts human-readable commands but also executes them.

An operating system consists of many parts, but the 2 core parts are the kernel and shell, we know that the kernel is like the atom of the operating system, the sole heart of the operating system. The kernel works a mediator between the software and hardware.

The shell on the other hand is more like the right hand of the kernel, it takes input from you in the form of commands, processes it, and then gives an output. The shell is retrieved via the terminal that runs it. Shell also provides an interface through which a user works on programs and scripts.
Types of shell

Shell is broadly classified into 2 categories:

1. Command line shell

The shell can be accessed by using a command-line interface, and we all know what a command line is. It is nothing but the terminal in Linux – the lean, mean coding machine. The terminal is a special program to type in the human-readable commands such as “cat”, “ls”, “cd”, “pwd”, “mkdir”, and a thousand more!

When you execute the commands, the result is then displayed on the terminal to the user. The terminal is powerful and allows users to store commands in a file and execute them together. Linux is not the only operating system with a command line, even windows had the command prompt and so doe mac OS

The command line is a boon for developers and administrators, but it may not be everyone’s cup of coffee as memorizing so many command sand and an even longer list of options is not an easy task. That is why there are 2 options for the shell so that users can use what they prefer most.

2. Graphical shell

The graphical shell is nothing but the GUI – Graphical interface design. The graphical shell provides an interface for manipulating programs based on the graphical user interface. The GUI allows users to do bath tasks that the terminal can and can not do.

For example, you can do tasks like allowing for operations such as opening, closing, moving, and resizing windows, as well as switching focus between windows and more which the terminal can’t. The main advantage of the GUI is that users need not type commands for every small task.

There are various shells that are available for Linux based operating systems, let us look at some of them:

1. BASH (Bourne Again SHell)

The bash shell is the most loved and commonly used shell in Linux-based operating systems. It is a default login shell in Linux systems and in macOS, however, it can also be installed on Mi9crosoft Windows.

The prompt for the bash shell is a dollar sign ($). The bash shell is a derivative of the Bourne shell, other derivatives of the Bourne shell include POSIX and Korn.

2. KSH (Korn SHell)

The Korn shell is also derived from the Bourne shell but is the base for POSIX. It was written, designed, and developed by David Korn in the early 1980s Some features of KSH are:

a. It provides object-oriented programing since ksh93t.
b. It has many mathematical and dynamic search functions.
c. it is very similar to C language and even has C-language-like expressions
d. You get a choice of 3 command line editing styes: vi, Emacs, and Gosling.
e. KSH includes reference variables and hierarchically nested variables.
f. It has associative arrays and built-in floating-point arithmetic operators
g. the Korn shell provides process substitution and process redirection.

3. CSH (C shell)

The C shell was written, designed, and developed at the University of California by Bill Joy. J8ust like bash has the prompt “$”, chs has the prompt “%”. The C shell was developed to be very similar to the C programming language, it also includes useful programming features like in-built support for arithmetic operations

The C shell feature ‘aliases’ and command history which was missing in different types of shells in Linux like the Bourne shell. The complete pathname for the C shell is /bin/sch.

There are many other shells available like:

  • ZSH (Z shell)
  • Fish Shell
  • POSIX
  • TENEX

What is shell scripting?

We saw that shells are interactive, they accept commands as input from users and execute them. But if we want to execute a bunch of commands again and again (like a loop), we have to type in all commands each time in the terminal.

To avoid this, the shell can also take in the commands as the input from a file, where we can compile all of these commands and execute them. These files are called Shell programs or shell scripts and have the extension of “.sh”.

Shell programs, just like any other programming language in the world, have a specific syntax and a set of rules. A shell script contains the following elements:

  • Keywords: if, else, break continue, etc.
  • Commands: cd, ls, echo, touch, cat, pwd, mkdir, etc.
  • Loops: if…then…else, while…do, do…while, case, etc.
  • Functions

We will look at each of the above-mentioned and more in detail in the practical part.

Why use shell programming?

There are a gazillion reasons why you should use shell programming, here are a few:

1. Avoids repetitive work and automation
2. Helps in system monitoring
3. Used for routine backups
4. Adding new functionality to shell
5. Creating custom filters
7. Helps in automating various tasks
8. Changing time and date
9. Printing current working directory
10. Scheduling jobs

Advantages of shell programming

Again, if we start writing the advantages of the list advantages of shell programming, it may never end, nonetheless here are 8 advantages of it:

  • Easy to use
  • Portable
  • Qiuck start
  • Interactive debugging
  • Same syntax as that of command line
  • Avoids repetitive work and automation
  • Shell scripting is much quicker than writing commands in the terminal
  • Simple up learn

Disadvantages of shell programming

They say that every good thing has its negatives, which also hold true for shell programming, here are some of its disadvantages:

  • Slow execution speed
  • Not suited for large and complex tasks
  • Design flaws within the language syntax
  • Provides minimal data structure, unlike other scripting languages
  • Prone to costly errors

Creating a shell program

We saw that to write a shell program we need to write it in a “.sh” file, meaning that a regular “.txt” or “.odt” or “.doc” will not suffice. Now there are a hundred ways to create a “.sh” file, let us look at some alternatives:

1. Using ‘gedit’

One method of creating a “.sh” file is by using the edit command. You can directly create and open a “.sh” file by specifying the name of the file as shown below, or you can simply use the edit command and save the file and name it later.

using gedit to create a shell script

You must be careful while naming your file because if you write the name of an already existing file with the command, it will open the existing file instead of creating one.

2. Using nano editor

Another method to create a “.sh” file is by using the nano editor in Linux-based operating systems. It works similar to the gedit command where you specify the name of the file you want to create next to the command.

using nano to create a shell script

Similar to the gedit command, even the nano command will open the existing file instead of creating a new one if you enter the name of an already existing file.

3. Using Vi editor

We all know that the Vi editor is a really powerful editor for text manipulation, but not that easy for text creation, meaning it will be even harder to write shell programs in it. Nonetheless, to create a “.sh” file using the ‘vi’ command, specify the name of the file after the Vi command as shown below:

using vi editor to create a shell script

Even the Vi editor will open the existing file if you enter the name of an already existing file.

4. Using the GUI

We know that all the distributions of Linux come with LibreOffice preinstalled, you can simply open a new file, write your program, and while saving your file, simply add the extension “.sh” to your filename as shown:

using gui to create a shell script

These are just some of the ways you can use to create a “.sh” file to write your shell program in. Now that we have laid down the fundamentals, let us jump into the theoretical part as we look at things like variables, expression loops, and more.

Printing “Hello world”

Let us kick start our shell programming journey by starting with the cliched “Hello world” program. Our objective is very simple and straightforward, and all we need to do is print the text “Hello world”

To do so, write the following piece of code in your “.sh” file:

shell program that prints hello world

The above code includes just 2 lines (although it is technically one), the first line must be written in all the shell programs, it simply specifies the shell we are using, in this case, it is the bash shell.

OK, now that we have written and saved our code, how do we execute it? Well, we simply type the command sh followed by the name of the file you save it in as follows:

sh <filename>.sh

output of the shell program that prints hello world

And voila! We just printed “Hello ”

Writing comments in the shell programs

We all know that writing comments is one of the most important habits while writing a code, we write it in order to understand what is actually happening. In shell programming, we write comments starting with a hash “#”, this makes these lines nonexecutable.

Printing using the echo command

As we have seen, the echo command is used to print out a specified message in the terminal, here is an example:

shell program depicting how to use the echo command

The shell program above will print out the following output:

output of the shell program showing the use of echo command

Variables in shell programming

Variables are the building blocks of any program, they store a value, and you can even tinker with this value at any time. Assigning a value is extremely easy in shell programming, in fact so easy that you don’t even have to initialize them like in C programming language.

To assign a variable simply follow the syntax shown below:

<varianle name> = <value>

And when you take up the name of this variable in any other parts of your program, be sure to use the dollar sign before it

For example, in the program shown below the value of x is 10 and it is later printed using the echo command (note the dollar sign before ‘x’):

shell program that initializes and prints a variable

output of the shell program that initializes and prints a variable

You can even print some text before the number to give a better understanding of the output as shown:

shell program that prints a string before the variable

output of the shell program that prints a string before the variable

We can also create string variables in the same way:
shell program that creates a string variableoutput of the shell program that creates a string variable

We can create many variables like float, integers, strings and so many more in a similar fashion.
When we speak of variables, we also talk about the predefined variables in the system called the “environmental variables”. We can also print these variables by incorporating them into our program, here is an example:

shell program that prints environmental variables

The command above prints the environmental variables BASH, USERNAME, HOME, and PWD and I did not even assign them:

output of the shell program that prints environmental variables

Reading input from the user

We can read the input from the user by using the keyword “read” followed by the variable you want to assign it to. For example the statement “read x” will read the user’s input and store it in the variable “x”.

shell program that reads input from the user

The shell program shown above will read the number entered by the user into the variable x and then print it out as shown:

output of the shell program that reads input from the user

You can also read strings in the same way:

shell program that reads input string from the user

In the shell program shown above, the user is asked for their first name and last name, these values are stored into the variables “a” and “b” respectively, then both the variables were printed one after the other.

output of the shell program that reads input string from the user

Expressions in shell programming

Now that we have learned how to deal with variables and how to read the input from users, let us now understand how expressions work in shell programming. Here they are not as simple as writing “2+3”, instead, you have to make use of the keyword “`expr”

You can even save an expression in a variable and access it later as shown:

shell program that uses expressions

output of the shell program that uses expressions

Similarly, you can even operate on variables as shown below:

shell program that operates on variables

And upon running the above code, we get the following output:

output of the shell program that operates on variables

Operators in shell programming

When we are using expressions, we obviously have some operators to operate on. Operators are of 3 types, arithmetic and relational, and logical, let us look at each of them:

The arithmetic operators are:

1. Addition (+)
2. Subtraction (-)
3. Division (/)
4. Multiplication (\*)

As you can see everything is in traditional style except for the multiplication operator, let us look at one example of it to clarify:

shell program that multiplies two variables

The shell program shown above will print the following output:

output of the shell program that mutiplies two variables

The relational operators are:

1. Greater than (-gt)
2. Less than (-lt)
3. greater than or equal to (-ge)
4. Less than or equal to (-le)
5. Equal to (-eq)
6. Not equal to (-ne)

The logical operators are:

1. Logical and (&&)
2. Logical or (||)
3. Not equal to (!)

We will look at examples of these when using loops in shell programming.

“If -else” statement in shell programming

Just like every other programming language, shell programming also had lupus and if-else statements. Let us first look at the syntax of the if-else statements:

1. “if … then” statement

If <condition>;
then
<arguments>
Fi

shell program using if then statement

Upon executing the program shown above, we get the following output:

output of the shell program using if then statement

2. “if … then … else” statement

If <condition>
Then
<arguments>
Else
<arguments>
Fi

 

shell program using if then else statement

The above program will give the following output:

output of the shell program using if then else statement

3. “if … then … elseif … then … else” statement

If <condition>
Then
<arguments>
Elseif <condition>
Then
<arguments>

Else
<arguments>
Fi

shell program using if then elseif then else statements

Upon executing the program shown above, we get the following output:

output of the shell program using if then elseif then else statements

4. Nested if

We can also nest one if loop inside another if loop, to further narrow down the condition, the following is a really beautiful example that illustrated if loops using all of the information we learned till now like environment variables, logical operators, nested if, else, comments and more:

shell program showcasing nested if

Upon executing the program shown above, we get the following output:

output of the shell program showcasing nested if

Switch case in shell programming

In shell programming, we can use multiple if-else statements, but this is not the best solution when all of the branches depend on the value of a single variable.

In such cases, we use “case”. In shell programming Just like if-else statements, we have switch-esac statements. Before we see an example, let us look at how it works.

The case statement is given an expression to evaluate and several different statements to execute based on the value of the expression. The program checks each case against the value of the expression until a match is found, if it all a match is not found, it simply exits without performing any action.

The following is the syntax followed while writing case statements:

case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac

Now, let us look at an example of the case statement in action:

shell program showcasing switch case

The output of the above-shown shell program will be:

output of the shell program showcasing switch case

Loops in shell programming

Just like every other programming language, shell programming also has loops, namely for loop, while loop, and do-while loop. Before we look at some examples of each let us look at the difference between while loop and do while loop.

The while loop checks the condition first and executes a set of commands while it is true, and exits when false. The do-while loop on the other hand first executes the set of arguments and only then checks the condition. This means that the minimum number of times you can execute a do-while loop is once. Let us now look at one example for each.

For loop:

shell program showcasing for loop

The output of the above-shown shell program will be:

output of the shell program showcasing for loop

While loop:

shell program showcasing while loop

The output of the above-shown shell program will be:

output of the shell program showcasing while loop

Do while loop:

shell program showcasing do while loop

The output of the above-shown shell program will be:

output of the shell program showcasing do while loop

Summary

You have now learned what shell programming is as we have gone straight from ground 0 by looking at what a shell is and discussing the types of shell. We also saw what shell programming is, why to use it, and a couple of its advantages and disadvantages of it.

We have then jumped from theoretical to practical and discussed various topics like variables, expressions, operators, many kinds of if-else scenarios, case statements, and loops.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *