top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Shell Scripting Tutorial

Shell scripting is a powerful skill that empowers users to interact with their operating systems efficiently and automate repetitive tasks. In this Shell Scripting Tutorial, we will delve into the world of shell scripting, exploring its various aspects and equipping you with the knowledge to become proficient in this essential tool.

Overview

At its core, shell scripting involves creating scripts that utilize the command-line interface (CLI) to execute a series of commands. These scripts can be written in various shell languages, such as Bash, and offer a wide range of functionalities. Let's start by understanding the key components that form the foundation of shell scripting.

What is Kernel?

The kernel is the core component of an operating system. It is responsible for managing the system's resources, such as the central processing unit (CPU), memory, and input/output devices. The kernel acts as an intermediary between the hardware and software, facilitating communication between them.

When a user interacts with the operating system by running commands or executing programs, the requests are handled by the kernel.

The kernel also plays a crucial role in ensuring that different processes running on the system are isolated from one another, preventing them from interfering with each other's memory or resources. 

What is Shell?

A shell is a user interface that allows users to interact with an operating system. It acts as a command-line interpreter, taking input from users in the form of text-based commands and executing them to perform various tasks. The shell is a crucial bridge between the user and the operating system's kernel.

When a user opens a terminal on a Unix-like system or a command prompt on Windows, they are interacting with a shell. The shell interprets the commands entered by the user and communicates with the operating system's kernel to execute those commands.

The primary function of a shell is to provide a way for users to interact with the operating system without the need for a graphical user interface. 

Categories of Shell

There are two main categories of shells:

  1. Command Line Shell:

Command line shells, as the name suggests, allow users to interact with the system by entering text-based commands. Bash (Bourne Again SHell) is one of the most popular command-line shells and is the default shell for many Unix-like systems.

The "ls" command is run with the "-l" option in the screenshot up top. It will display a long listing of every file in the current working directory.

It can be challenging for novices to learn so many commands while using a command line shell. It is highly strong; users can save commands in a file and execute them all at once. 

Any repetitive task can then be mechanized with ease in this way. In Windows, these files are typically referred to as batch files, and in Linux/macOS systems, as shell scripts.

  1. Graphical Shell:

Graphical shells provide a user-friendly graphical interface for interacting with the operating system. These shells often use windows, icons, and menus (WIM) to facilitate user interactions. Examples include GNOME Shell and Windows PowerShell.

By enabling actions like opening, closing, moving, and resizing windows, as well as switching focus between windows, graphical shells offer a way to manipulate programs with a graphical user interface (GUI). A good example of an operating system that offers a graphical user interface (GUI) for application interaction is Windows OS or Ubuntu OS. 

For Linux systems, a number of shells are available, including:

  • The most popular shell in Linux systems is BASH (Bourne Again SHell). In Linux and macOS systems, it serves as the standard login shell. Windows OS supports installing it as well.

  • The syntax and usage of the C shell are extremely similar to those of the C programming language.

  • The KSH (Korn Shell) served as the foundation for the POSIX Shell standard requirements and other elements.

Each shell performs the same purpose, although they each recognize various commands and offer various built-in features.

What is a Terminal?

A terminal is a program that provides users with a text-based interface to interact with the shell. It allows users to enter commands and view the results of those commands in a command-line environment. The terminal acts as a window into the shell, providing an interactive way to work with the system. Simply type "terminal" into the search box and double-click to open the terminal.

You can view how Red Hat Linux's terminal appears here.

Common commands for the terminal.

  1. ls: List files and directories in the current directory.

  2. cd: Change directory. Use cd <directory> to navigate to a specific directory.

  3. pwd: Print the working directory, showing the current location in the file system.

  4. mkdir: Create a new directory. Use mkdir <directory> to make a new folder.

  5. rm: Remove files or directories. Use rm <file> to delete a file and rm -r <directory> to remove a directory (including its contents).

  6. cp: Copy files or directories. Use cp <source> <destination> to copy a file or folder to a specified location.

  7. mv: Move or rename files or directories. Use mv <source> <destination> to move a file or folder to a new location or rename it.

  8. cat: Concatenate and display the contents of a file.

  9. more or less: Display file content one screen at a time, allowing you to scroll through it.

  10. grep: Search for a pattern in a file. For example, grep "keyword" file.txt searches for "keyword" in file.txt.

What is Shell Scripting

Shell scripting involves writing scripts using shell languages to automate tasks and perform complex operations. Shell scripts can be used to execute a series of commands in a sequence, making it easy to repeat tasks and save time. For instance, you can write a shell script to back up files or perform system maintenance tasks.

To avoid doing this repetitive labor, we can write these commands in a file and execute them in a shell, as a shell can also accept commands as input from files. Shell Scripts or Shell Programs are the names of these files. 

The components of a shell script include the following:

  • Shell Keywords: break, if, and else.

  • cd, ls, echo, pwd, touch, and other shell commands.

  • Functions

  • Control flow, including case, shell, and if-then-else loops, etc.

Unix shell scripting

Unix shell scripting is the process of writing scripts or programs that utilize Unix shell commands to automate tasks or perform specific operations in a Unix or Unix-like operating system. The shell is a command-line interface that allows users to interact with the operating system by executing commands. Common Unix shells include Bash (Bourne Again SHell), C Shell (csh), Korn Shell (ksh), and Z Shell (zsh).

Here are some key concepts and features of Unix shell scripting:

  1. Shell Script File: A shell script is a plain text file that contains a series of shell commands and other programming constructs. The script is executed sequentially, one command at a time.

  1. Shebang: The first line of a shell script should start with a "shebang" (#!) followed by the path to the shell interpreter. For example, #!/bin/bash indicates that the script should be interpreted using the Bash shell.

  1. Variables: Shell scripts can define and use variables to store data. Variable names are case-sensitive, and you can assign values to them using the = operator.

  2. Command Substitution: Shell scripts can capture the output of a command and use it as a variable value or in other parts of the script. This is done using backticks (`) or the $() syntax.

  3. Control Structures: Shell scripts support various control structures like conditionals (if, else, elif), loops (for, while), and case statements (case) to control the flow of execution.

  4. Input/Output Redirection: You can redirect input and output streams of commands in shell scripts using operators like <, >, >>, and pipes (|).

  5. Functions: Shell scripts can define functions to group commands and make the code modular and reusable.

  6. Comments: You can add comments in shell scripts using the # symbol. Comments are ignored by the interpreter and are used to provide explanations and documentation.

  7. Permissions: Before executing a shell script, you may need to set appropriate permissions using chmod to make the file executable.

  8. Execution: To run a shell script, you can use the command ./scriptname if the current directory is in the PATH, or you can specify the full path to the script.

Example of a simple Bash shell script that prints "Hello, World!":

To execute this script, save it to a file (e.g., hello.sh) and make it executable with chmod +x hello.sh. Then, run it using ./hello.sh.

Shell scripting examples

  1. This script checks if a file exists and if it's a directory or a regular file.

#!/bin/bash

echo "Enter a file/directory path: "
read path

if [ -e "$path" ]; then
  if [ -f "$path" ]; then
    echo "$path is a regular file."
  elif [ -d "$path" ]; then
    echo "$path is a directory."
  else
    echo "Unknown file type."
  fi
else
  echo "$path does not exist."
fi

If the user enters an existing regular file path, the output will be:

  1. This script defines a function to check if a number is even or odd.

#!/bin/bash

is_even_odd() {
  if (( $1 % 2 == 0 )); then
    echo "$1 is even."
  else
    echo "$1 is odd."
  fi
}

echo "Enter a number: "
read num
is_even_odd $num

Assume the script is executed, and the user enters the number 7 when prompted. The output will be as follows:

In this example, the script reads the input number 7 from the user using the read command. It then calls the function is_even_odd with the value of num (which is 7) as an argument. Inside the function, it performs the check (( $1 % 2 == 0 )) to determine whether the number is even or odd. Since 7 % 2 equals 1, the condition $1 % 2 == 0 evaluates to false, and the script prints "7 is odd."

Why do we need Shell Scripts?

Shell scripts offer several advantages:

  • Automation: Shell scripts automate repetitive tasks, reducing manual intervention and saving time.

  • Batch Processing: They allow batch processing of commands, ideal for handling large datasets or complex operations.

  • System Administration: Shell scripts are commonly used for system administration tasks, making it easier to manage multiple systems efficiently.

Disadvantages of Shell Scripts

  • Performance: Complex tasks can be slower when executed through shell scripts compared to compiled programs.

  • Limited Portability: Shell scripts might not work across different shell environments or operating systems.

  • Security Risks: If not written carefully, shell scripts can pose security risks due to potential vulnerabilities.

Conclusion

Mastering shell scripting is an invaluable skill for any developer or system administrator. It enables you to streamline your workflow, automate tedious tasks, and gain a deeper understanding of how your operating system works. Embrace the world of shell scripting, and you'll find yourself unleashing the true potential of your system. We hope that this Shell scripting tutorial for beginners.Happy scripting!

FAQs

  1. How do I pass command-line arguments to a shell script?

Command-line arguments allow you to provide input to a shell script when executing it from the command line. Within a shell script, you can access these arguments using special variables: $1 for the first argument, $2 for the second argument, and so on. You can access all the arguments at once using $@ or $*.

  1. How can I redirect both standard output and standard error to a file?

In shell scripting, you can redirect standard output (stdout) and standard error (stderr) to different files or the same file. To redirect both to the same file, you can use the following syntax: command > output.log 2>&1. This redirects stdout to output.log and then redirects stderr to the same file descriptor as stdout, effectively merging both streams into the file.

  1. How do I create a reusable library of functions in shell scripting?

Shell scripts can become more efficient and modular by creating libraries of reusable functions. To do this, you can create a separate file containing your functions (e.g., mylibrary.sh), and then use the source or . command to include the functions in other scripts. 

Leave a Reply

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