Open In App

Introduction to Linux Shell and Shell Scripting

Last Updated : 16 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understanding shell scripting we have to get familiar with the following terminologies:

  • Kernel
  • Shell
  • Terminal

What is Kernel?

The kernel is a computer program that is the core of a computer’s operating system, with complete control over everything in the system. It manages the following resources of the Linux system –

  • File management
  • Process management
  • I/O management
  • Memory management
  • Device management etc.

It is often mistaken that Linus Torvalds has developed Linux OS, but actually, he is only responsible for the development of the Linux kernel.

Complete Linux system = Kernel + GNU system utilities and libraries + other management scripts + installation scripts.

What is Shell?

A shell is a special user program that provides an interface for the user to use operating system services. Shell accepts human-readable commands from users and converts them into something which the kernel can understand. It is a command language interpreter that executes commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or starts the terminal.

Linux Shell

Linux Shell

Shell is broadly classified into two categories –

  • Command Line Shell
  • Graphical shell

Command Line Shell

Shell can be accessed by users using a command line interface. A special program called Terminal in Linux/macOS, or Command Prompt in Windows OS is provided to type in the human-readable commands such as “cat”, “ls” etc. and then it is being executed. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –

linux command line

linux command line

In the above screenshot “ls” command with “-l” option is executed. It will list all the files in the current working directory in a long listing format.
Working with a command line shell is a bit difficult for beginners because it’s hard to memorize so many commands. It is very powerful; it allows users to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems.

Graphical Shells

Graphical shells provide means for manipulating programs based on the graphical user interface (GUI), by allowing for operations such as opening, closing, moving, and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as a good example which provides GUI to the user for interacting with the program. Users do not need to type in commands for every action. A typical GUI in the Ubuntu system –

GUI Shell

GUI Shell

There are several shells are available for Linux systems like –

  • BASH (Bourne Again SHell) – It is the most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS.
  • CSH (C SHell) – The C shell’s syntax and its usage are very similar to the C programming language.
  • KSH (Korn SHell) – The Korn Shell was also the base for the POSIX Shell standard specifications etc.

Each shell does the same job but understands different commands and provides different built-in functions.

What is a terminal?

A program which is responsible for providing an interface to a user so that he/she can access the shell. It basically allows users to enter commands and see the output of those commands in a text-based interface. Large scripts that are written to automate and perform complex tasks are executed in the terminal.


To access the terminal, simply search in search box “terminal” and double-click it.

open terminal

open terminal

Here you can see how the terminal looks of Red Hat Linux.
 

terminal

terminal

Shell Scripting

Usually, shells are interactive, which means they accept commands as input from users and execute them. However, sometimes we want to execute a bunch of commands routinely, so we have to type in all commands each time in the terminal.

As a shell can also take commands as input from file, we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with `.sh` file extension e.g., myscript.sh.

A shell script has syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. It would be very easy to get started with it.

A shell script comprises the following elements –

  • Shell Keywords – if, else, break etc.
  • Shell commands – cd, ls, echo, pwd, touch etc.
  • Functions
  • Control flow – if..then..else, case and shell loops etc.

Why do we need shell scripts?

There are many reasons to write shell scripts:

  • To avoid repetitive work and automation
  • System admins use shell scripting for routine backups.
  • System monitoring
  • Adding new functionality to the shell etc.

Some Advantages of shell scripts

  • The command and syntax are exactly the same as those directly entered in the command line, so programmers do not need to switch to entirely different syntax
  • Writing shell scripts are much quicker
  • Quick start
  • Interactive debugging etc.

Some Disadvantages of shell scripts

  • Prone to costly errors, a single mistake can change the command which might be harmful.
  • Slow execution speed
  • Design flaws within the language syntax or implementation
  • Not well suited for large and complex task
  • Provide minimal data structure unlike other scripting languages. etc.

Simple demo of shell scripting using Bash Shell

If you work on a terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute a command like this as shown below to get to the “python” directory:

get to the “python” directory:

get to the “python” directory:

It is quite frustrating, so why not we can have a utility where we just have to type the name of directory and we can directly jump to that without executing the “cd ../” command again and again. Save the script as “jump.sh

bash
# !/bin/bash

# A simple bash script to move up to desired directory level directly

function jump()
{
    # original value of Internal Field Separator
    OLDIFS=$IFS

    # setting field separator to "/"
    IFS=/

    # converting working path into array of directories in path
    # eg. /my/path/is/like/this
    # into [, my, path, is, like, this]
    path_arr=($PWD)

    # setting IFS to original value
    IFS=$OLDIFS

    local pos=-1

    # ${path_arr[@]} gives all the values in path_arr
    for dir in "${path_arr[@]}"
    do
        # find the number of directories to move up to
        # reach at target directory
        pos=$[$pos+1]
        if [ "$1" = "$dir" ];then

            # length of the path_arr
            dir_in_path=${#path_arr[@]}

            #current working directory
            cwd=$PWD
            limit=$[$dir_in_path-$pos-1]
            for ((i=0; i<limit; i++))
            do
                cwd=$cwd/..
            done
            cd $cwd
            break
        fi
    done
}

For now, we cannot execute our shell script because it does not have permissions. We have to make it executable by typing following command –

$ chmod +x path/to/our/file/jump.sh

Now to make this available on every terminal session, we have to put this in “.bashrc” file.

.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose of a .bashrc file is to provide a place where you can set up variables, functions, and aliases, define our prompt, and define other settings that we want to use whenever we open a new terminal window.

Now open the terminal and type the following command:

$ echo “source ~/path/to/our/file/jump.sh”>> ~/.bashrc

Now open your terminal and try out new “jump” functionality by typing following command-

$ jump dir_name

just like the below screenshot:

jump dir_name

jump dir_name

Conclusion

In this article, we learned about the essential parts of Linux systems: the kernel, which controls everything, the shell, which lets us interact with the operating system, and the terminal, our interface to give commands. We explored command line and graphical shells, like BASH, and understood that the terminal is where we type in our commands. The article introduced shell scripting, a way to automate tasks using simple scripts, and discussed the advantages and disadvantages of using them. A practical example demonstrated creating a script for quick directory navigation. Finally, we saw how to make the script work and become accessible in every terminal session. This article is a beginner-friendly guide to understanding and using Linux shells and shell scripting.linux is good language it is written in linux language



Similar Reads

Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has fe
3 min read
Bash Scripting - Introduction to Bash and Bash Scripting
Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System.  It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to a
10 min read
Shell Scripting - Interactive and Non-Interactive Shell
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Restricted Shell
Shell is one of the most important and powerful tools available in GNU/Linux-based systems. One can control the entire system if used correctly, this exact feature makes the shell a double-edged sword. It can potentially harm the system if one executes a system command without knowing its underlying details and consequences. To prevent this we use
5 min read
Shell Scripting - Default Shell Variable Value
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Shell Signals Values
Prerequisites: Processes, Bash Scripting, Shell Function Library Signals help the operating system to communicate with processes and vice-versa. Signals are also generated when processes don't function properly or try to access prohibited memory. Different signals are mapped to different numbers which are referred to as signal values. The Linux OS
6 min read
Shell Scripting - Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing
6 min read
Bash Scripting - How to Run Bash Scripting in Terminal
In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a t
2 min read
Bash Scripting - Working of Bash Scripting
Bash Scripting is a crucial component of Linux's process automation. You can write a series of commands in a file and then execute them using scripting. A Bash script is a plain text file with a set of commands inside of it. These commands are a combination of ones we typically type on the command line ourselves (like ls or cp, for instance) and ot
6 min read
Shell Script to Show the Difference Between echo “$SHELL” and echo ‘$SHELL’
In shell scripting and Linux, the echo command is used to display text on the terminal or console. When used with the $SHELL variable, which contains the path of the current user's shell program, the output of the echo command can be different depending on whether the variable is enclosed in single or double quotes. echo "$SHELL" will expand the $S
4 min read
Shell Scripting - Difference between /dev/null and /dev/zero
Device files/nodes are special files that allow applications to interface with device drivers. I/O operations on device nodes are handled by the driver for that device. Device nodes are the standard mechanism for accessing hardware on Unix systems. Several device nodes are present on all Linux systems. Some of these device nodes are special - for e
3 min read
Shell Scripting - Standard Input, Output and Error
Working on Linux applications we have several ways to get information from outside and to put it inside: command line args, environment variables, files. All of these sources are legal and good. But it has a finite size. Another way to establish communication is standard streams: input stream (stdin) used for getting data from outside of the app, o
7 min read
Shell Scripting - Functions and it's types
Shell scripting is a powerful tool used to automate tasks in Unix-like operating systems. A shell serves as a command-line interpreter, and shell scripts often perform file manipulation, program execution, and text output. Here, we'll look into functions in shell scripting, exploring their structure, usage, and types to help you effectively incorpo
5 min read
Auto Logout in Linux Shell Using TMOUT Shell Variable
TMOUT is a Linux-Unix shell variable that provides the user security for their login session in the system. It provides the "Auto Logout Functionality" for the login shell in case of no activity for a specified time. Generally when the user leaves the Linux system idle (situation when a user doesn't perform any administrative task by running a comm
2 min read
How to protect Linux shell file using noclobber in bash shell?
Most Linux shells(bash, csh, ksh, tcsh) have a built-in file protection mechanism to prevent files from being overwritten accidentally. In this article, we will see how to prevent it by setting noclobber option. Clobbering Redirecting standard output to a file that already exists would overwrite the existing file content which will result in data l
2 min read
Array Basics Shell Scripting | Set 2 (Using Loops)
It is recommended to go through Array Basics Shell Scripting | Set-1 Introduction Suppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop and while loop. To Print the Static Array in Bash 1. By Using whi
3 min read
How to check if a directory or a file exists in system or not using Shell Scripting?
Shell scripting is really a powerful and dynamic way to automate your tasks. To test if a directory or file already exists in the system or not we can use shell scripting for the same along with test command. To proceed with the test script lets first check the test manual. To open a manual use the man command as follows: man test Right now we will
2 min read
Create a password generator using shell scripting
Creating a strong password is often a time-consuming task and even after creating a good password by yourself it gets brute-forced by hackers. In this article, we will learn how to create a strong password which fulfills all requirements including symbols, capitals length etc using a simple shell script in Linux. How to create a password generator
1 min read
Leap Year Program with Bash Shell Scripting in Windows
Accurately the Earth has 365.24 days per year, to correct the approximation and keep track of the Solar Calendar the idea of leap year has been introduced to Gregorian Calendar. A leap year comes once every four years. In contrast, it has 366 days with regular years, having 365 days. Mathematical approach to check:Every year is a Leap year if it is
1 min read
String Manipulation in Shell Scripting
String Manipulation is defined as performing several operations on a string resulting change in its contents. In Shell Scripting, this can be done in two ways: pure bash string manipulation, and string manipulation via external commands. Basics of pure bash string manipulation: 1. Assigning content to a variable and printing its content: In bash, '
4 min read
Shell Scripting - Test Constructs
Since 0 by UNIX tradition denotes "success," an if/then construct checks to see if the exit status of a list of commands is 0 and, if it is, runs one or more instructions. There is an exclusive command called [ (left bracket special character). It is a built-in synonym for test and is used for efficiency. This command uses the arguments as file tes
6 min read
Shell Scripting - Select Loop
The select loop is one of the categories of loops in bash programming. A select-loop in the shell can be stopped in two cases only if there is a break statement or a keyboard interrupt. The main objective of using a select loop is that it represents different data elements in the form of a numbered list to the user. The user can easily select one o
5 min read
Shell Scripting - Define #!/bin/bash
A shell provides an interface to connect with the system. When we use an operating system, we indirectly interact with the shell. While using a terminal every time on any Linux distribution system, we interact with the shell. The main function of the shell is to interpret or analyze Unix commands. A shell takes commands from the user and translates
3 min read
Shell Scripting - Command Substitution
A shell is an interface that helps users to connect with the system. Using a shell is equivalent to indirectly communicating with the operating system. In Linux distributed systems, each time we use the terminal, we connect with a shell. The job of a shell is to analyze Unix commands or instructions given by the user. This process involves taking c
4 min read
Shell Scripting - Substitution
There are certain expressions that convey special meanings. In other words, they are not what they look like. A shell carries out substitution whenever it encounters such expressions. Hence, substitution is defined as a mechanism carried out by a shell in which it substitutes the value of an expression with its actual value. Escape sequences: An es
3 min read
Shell Scripting - True Command
A shell provides an interface with the help of which users can interact with the system easily. To directly interact with a shell, we use an operating system. On a Unix-based operating system, every time we write a command using a terminal, we interact with the system. To interpret or analyze Unix commands, we use a shell. The main job of a shell i
3 min read
Shell Scripting - Variable Substitution
A shell is an interface that helps users to connect with the system. Using a shell is equivalent to indirectly communicating with the operating system. In Linux distributed systems, each time we use a terminal, we connect with a shell. The job of a shell is to analyze Unix commands or instructions given by the user. This process involves taking com
3 min read
Shell Scripting - Rules for Naming Variable Name
Variables are quite important in any script or program, so we need to understand what is the convention to name these variables. There are certain rules and standards to keep in mind while giving names to the variables in Shell scripting. In this article, we will discuss and list down all the rules and conventions to declare a variable name in Shel
4 min read
Shell Scripting - How to view Processes?
In this article, let's explore how we can view current processes running on a Linux Server. Linux machine gives users the option of multitasking hence naturally there will be multiple processes running on a session and also these processes are important fundamental components of Linux OS, Hence System Administrators may need to be aware of all proc
4 min read
Shell Scripting - Dialog Boxes
In this article, we will create a shell script that generates a Dialog Box with GUI generating a message to the user. What is a Dialog Box? A Dialog Box is a temporary window an application runs to convey important information to the users. These dialog boxes can be used to display warnings, errors, and also any additional inputs needed by the syst
7 min read
Article Tags :
three90RightbarBannerImg