15 Updated Shell Scripting Interview Questions and Answers: Freshers and Experienced

shell scripting interview questions and answers

When talking about customizable Operating Systems, Linux is the only name that comes up. Speaking of which, Shell Scripting is one of the most foundational skills required by recruiters. Especially when you want to become a DevOps Engineer, Shell Scripting is a core skill to master.

According to recent research conducted by Google, 77% of organizations currently deploy software or are planning to deploy software through DevOps. On top of that, the DevOps industry crossed 10.4 billion last year and is projected to grow at a CAGR of 19.7% from 2024 to 2028.

Therefore, it is the best decision ever to invest in a DevOps Engineer career for 2025.

To make it easy, we have compiled an updated list of the top 15 most-asked Shell Scripting interview questions for both freshers and experienced candidates looking for a better job in the industry.

Shell Scripting Interview Questions for Freshers

1. What is Shell Scripting? 

A shell script is a text file that contains a collection of command lines based on their order of execution. In other words, it is a computer program that is created to be run by a command-line interpreter (shell) called Unix Shell. Whenever a user adds a command, the shell script converts it into a language that is easily understood by the Kernel.

The process of adding commands on the shell script is called Shell Scripting. 

The following are the various purposes of using the shell script:

  • You can automate tasks with shell scripting. For example, you can create a customized Operating System based on your requirements. 
  • You can improve the efficiency of an existing software.
  • It also provides a consistent approach to system administration.

2. Why is Shell Scripting Used in DevOps?

There are several reasons why Shell Scripting is used in DevOps. Some of the most significant ones are mentioned as follows:

  • Automation

All the boring and repetitive tasks can be automated by using Shell Scripts thus, reducing manual error and effort. Since efficiency and consistency are the most important in DevOps, automation is crucial.

  • Integration

DevOps often needs to join different tools and systems. Shell scripts can work as a link joining various pieces and making workflows between them run on their own. 

  • Configuration Management 

Shell scripts have a role in setting up servers, applications, and infrastructure parts. This leads to a uniform and duplicable environment, which makes management and problem-solving easier.

  • Deployment and Testing

Shell scripts help to make deployment processes run on their own. This ensures that apps are set up the same way in different places. They also help with testing by running checks on their own and making sure deployments are correct.

  • System Administration

Shell scripts are a strong tool to handle system tasks. They let you do jobs like managing users, setting up services, and keeping an eye on how well the system is doing.

  • Flexibility

You can tailor shell scripts to meet specific needs. It’s easy to change and add to them as your requirements shift.

  • Portability

You can run shell scripts on different Unix-like systems without issues. This makes them a good fit for various setups.

Note: Check out our DevOps Master’s Program to learn everything about Linux and 13+ tools and technologies.

DevOps master program

3. What are Some of the Shell Scripting Examples?

Some of the most significant shell scripting examples are as follows:

  • Automated Deployment Shell Script

Creating a script to automate the deployment or configuration of applications to multiple servers.

Example: Here is a script to clone the Git repository that builds the application and runs it.
git clone https://your-git-repository.git

cd your-project

make clean && make

./your-application

  • File Transfer Shell Script

Creating a script to enable the transfer of files with security between servers that use SCP or SFTP. 

Example:

#!/bin/bash

# Set the source and destination servers

source_server=”user@source_server_ip”

dest_server=”user@dest_server_ip”

# Create a directory on the destination server (if needed)

ssh “$dest_server” mkdir -p /path/to/destination/directory

# Transfer files using SCP

scp -r /path/to/source/files “$dest_server:/path/to/destination/directory”

# Verify successful transfer

ssh “$dest_server” ls -l /path/to/destination/directory

  • Email Notification Shell Script

Creating a shell script to push email notifications for various events or alerts.

Example:

#!/bin/bash

send_email() {

  subject=”$1″

  body=”$2″

  recipient=”$3″

  # Email server settings

  smtp_server=”smtp.example.com”

  smtp_port=587

  smtp_user=”your_email@example.com”

  smtp_password=”your_email_password”

  # Send email

  echo “From: Your Name <your_email@example.com>\nTo: $recipient\nSubject: $subject\n\n$body” | sendmail “$recipient” -t

}

# Example usage

send_email “Deployment Status” “Deployment completed successfully.” “your_recipient@example.com”

Also Read: Best Scripting Tools for Automation and Efficiency

4. Mention the Different Types of Shells in Linux.

There are two main types of shells used in Linux. These are:

  • Bourne Shell
  • Strong emphasis on scripting and automation.
  • Provides a wide range of built-in commands and functions.
  • Supports conditional statements, loops, and input/output redirection.
  • It offers a flexible syntax for defining variables and functions.
  • Well-suited for system administration tasks and general-purpose scripting.
  • C-Shell
  • It is inspired by the C programming language, offering a more C-like syntax.
  • It provides some interactive features like command history, job control, and aliases.
  • This type of shell supports conditional statements, loops, and input/output redirection.
  • It has a different approach to the variable assignment and scoping compared to sh.

5. How can You Create and Execute a Shell Script?

The following are the important steps to create and execute a shell script from scratch:

  • You have to create a file with a .sh extension.
  • Then, you need to write your script with the help of shell commands.
  • The command is not fit for running yet. To make it executable, you need to use chmod +x filename.sh and run it with ./filename.sh.

6. What is Meant by Positional Parameters in Shell Scripting?

Positional parameters are a special type of parameter in shell scripting. These are referred to as arguments that are passed to a script when it’s executed. You can access a positional parameter in shell scripting simply by using the $ sign along with the parameter number starting from 1.

For example:

On using the following code:

#!/bin/bash

echo “Script name: $0”

echo “First argument: $1”

echo “Second argument: $2”

echo “Total arguments: $#”

echo “All arguments: $@”

And then saving it as myscript.sh, like the following:

./myscript.sh arg1 arg2 arg3

Will give you the following output:

Script name: ./myscript.sh

First argument: arg1

Second argument: arg2

Total arguments: 3

All arguments: arg1 arg2 arg3

7. How Would You Create a Shortcut in Linux?

You can use links in the Linux Operating System to create a shortcut in Linux. The following are the two types of links you can use:

  • Hard Link

Hard links are the types of links that have to be on the same file system as that of the file. Each of the hard-linked files is given the same inode value as the original file. Even if you delete the original file, the hard link is not affected.

You can create a hard link by using the following command:

$ ln  [original filename] [link name] 

  • Soft Link

A soft link, or symbolic link, in shell scripting, is a file that acts as a pointer to another file or directory. It allows you to create shortcuts, enabling access to the target file without duplicating it. Soft links can point to files on different file systems and can lead to broken links if the target is moved or deleted.

You can create a soft link by using the following command:

$ ln  -s [original filename] [link name]

8. What are the Different Types of Loops in Shell Scripting?

There are three main types of loops in shell scripting. These are:

  • For loop:

When you need to execute a specific block of code for a particular number of times, the For loop is used.

  • While loop:

The While loop is often used while using the True-False condition. It executes a specific block of code

  • Until loop:

Even the Until loop executes on the basis of a True-False condition. It executes a specific block of code until a condition becomes true. 

Shell Scripting Interview Questions for experienced

9. How Can You Check the Exit Status of a Command?

The exit status of a command can be checked with the help of $? variable. The exit status is measured in numbers. A zero exit status shows success whereas a non-zero exit status represents a potential error.

10. What is the difference between = and == in shell scripting?

In shell scripting, both = and == are used for string comparison, but there are nuances depending on the context.

  • =: This operator is used to assign values to variables. For example:

 my_var=”Hello”

  • ==: This is often used in conditional expressions within [[ ]] for string comparison, although it can also work with [ (test command) ]. For example:

if [[ $my_var == “Hello” ]]; then

    echo “Matched!”

fi

Note: Use = for assignment and == for comparison in conditional expressions. The double brackets [[ ]] provide more features and avoid issues with word splitting and pathname expansion.

11. What is the Use of trap in Shell Scripting?

In shell scripting, the trap command catches signals and acts on a command upon receipt of that signal. It is primarily used to clean up upon termination or interruption of a script.

Example:

trap ‘echo “Script interrupted”; exit’ SIGINT SIGTERM

while true; do

    echo “Running.”

    sleep 1

done

In the above example, the script will print “Script interrupted” and then exit if it is interrupted with a Ctrl+C by the user.

Note: Use trap to render your scripts robust at interrupt so cleanup of resources or saving of state may take place, as needed.

12. Explain the Process of Substitution. How is It Used?

Process substitution allows you to make a command think that its input comes from or its output goes to a file, whereas actually, it is the output produced by another command. 

Syntax: command <(other_command) 

Example:

diff <(ls dir1) <(ls dir2) 

In the above example, diff compares the results of listing two different directories without using temporary files.

Note: Process substitution can simplify scripts by avoiding the use of an intermediate file and also will optimize performance because it avoids I/O.

13. What is Meant by here Documents? How Can You Use Them?

here documents which are also called Heredocs are a special kind of quoting that allows you to write multiple-line strings directly in your script or command. It is especially useful when you want to pass several lines of text or even commands to utilities like cat, sed, or awk.

Syntax:

command <<EOF

line 1

line 2

EOF

Example:

cat <<EOF > myfile.txt

This is line 1.

This is line 2.

EOF

In the example above, cat creates a file called myfile.txt containing two lines of text.

14. What is Meant by a Crontab? How Many Fields are Present in a Crontab File?

A crontab or cron table is a configuration file that outlines the schedule that the cron daemon should execute and indicates the job to be executed in Unix-like operating systems. It allows for running scripts or commands at given periods-momentarily, daily, weekly, or monthly.

An ordinary crontab file will contain five time and date fields and finally the command to be executed. The fields are as follows:

  1. Minute (0-59)
  2. Hour (0-23)
  3. Day of Month (1-31)
  4. Month (1-12)
  5. Day of Week (0-7) (Sunday is both 0 and 7)

After the above five fields, you specify the command you want to run.

Note: There are mainly five fields in a crontab file. However, there is also a sixth field that contains the command that needs to be executed.

15. How can you use a shell script to monitor disk space usage and send an alert if the usage exceeds a specified threshold? Provide a detailed explanation of the script components.

To write a shell script that monitors disk usage and sends an alert if the usage is greater than a predefined threshold, follow these steps:

  1. Define the Threshold

Define the threshold at which your disk space usage should trigger an alert. You can define this in percentage.

THRESHOLD=90

  1. Get Disk Usage Information

To check disk usage, use df. In df, -h is the option for showing output in human-readable format, whereas –output gives specified columns.

USAGE=$(df / | grep / | awk ‘{ print $5 }’ | sed ‘s/%//g’)

– df /: The command to check usage of the root directory.

– grep /: This will filter out the output to get the line containing the root filesystem.

– awk ‘{ print $5 }’: Prints the fifth column, which is the percentage used.

– sed ‘s/%//g’: Removes the percentage sign so that numerical comparison may be done.

  1. Compare Usage to Threshold

Check if the disk usage in the current reading is greater than or equal to the threshold set.

if [ “$USAGE” -ge “$THRESHOLD” ]; then

  1. Sending Alert

If it is greater than the threshold, send an alert. This may be simply an email notification, or to some logging system.

Sending email via mail:

echo “Disk space usage is critically high: ${USAGE}% used.” | mail -s “Disk Space Alert” admin@example.com

  1. Full Script

Herein is how you can piece it together in a shell script:

#!/bin/bash

# Set threshold for disk usage

THRESHOLD=90

# Get present disk usage in percentage

USAGE=$(df / | grep / | awk ‘{ print $5 }’ | sed ‘s/%//g’)

# Check if the current usage is greater than the threshold

if [ “$USAGE” -ge “$THRESHOLD” ]; then

    # Send an alert email.

    echo “Disk space usage is critically high: ${USAGE}% used.” | mail -s “Disk Space Alert” admin@example.com

fi

Explanation of Components:

  • Shebang (#!/bin/bash): This line ensures this script runs under the Bash shell.
  • Variables: The Script uses two variables, one named THRESHOLD to store the threshold value of disk usage in percentage, and another one named USAGE to store the current usage.
  • Command Substitution: We have used command substitution, enabled by the use of the dollar-sign/parentheses notation: $(). This is very handy to capture the output of commands directly into variables.
  • Conditional Statement: The conditional statement will check whether the current usage is greater than or equal to the threshold.

Alert Mechanism: The script herein uses the mail command, meaning a mail transfer agent should be installed on the server.

Deployment

Give execute permissions to your script by running the following in your terminal:

“`bash

chmod +x disk_monitor.sh

“`

Then you may want to schedule a cron job to execute this script daily – or at regular periods of your choice:

“`bash

0 0 * * * /path/to/disk_monitor.sh

“`

This will serve to provide you with timely alerts when disk usage starts creating problems, so you may manage the system resources in time.

Learn Directly from DevOps Engineers 100% Online

Shell Scripting makes up an important part of learning a customizable Operating System such as Linux. Even while preparing to become a job-oriented DevOps Engineer, shell scripting is an important part of the course curriculum. 

If you’re interested in learning directly from Engineers with more than 12 years of hands-on industry experience in the DevOps industry, you must check out our strategically-created DevOps Master’s Program

Searching for what’s covered in our DevOps Master’s Program? Check out the video here:

Leave a Comment

Attend Your First Free Demo Class

Fill out the form now to experience live classes with us. Learn Directly from Engineers working in big tech giants.