Shell Scripting Interview Questions and Answers 2024

  • By Gandhar Bodas
  • January 31, 2024
  • Linux
Shell Scripting Interview Questions and Answers 2024

Shell Scripting Interview Questions and Answers 2024

Master essential shell scripting concepts, command-line utilities, and scripting best practices. Stay ahead in your interview with insights into the latest trends and expectations in shell scripting. Prepare for success in shell scripting interview questions and answers 2024.

Q1) What is Shell?

🡺

Diagram are as below:

Shell Scripting Interview Questions and Answers 2024

User/applications O.S.

 

Interface Shell

Kernel

      Hardware

  1. Shell is a responsibility to read commands provided by the user.
  2. Shell will check whether the command is valid is or not.
  3. Shell will check whether the command is properly used or not.
  4. If everything is proper then shell interprets (commands) that command into kernel understandable form and handover that converted command to kernel.

Note: All above activities will take care by Shell.

  1. Now finally kernel is responsible to execute that command with the help of hardware.
  2. Shell acts as interface between user and kernel.
  3. Shell + kernel is nothing but Operating System.

Note: Shell acts as interface between user and kernel.

Kernel acts as interface between shell and hardware

 

For Free Demo classes Call:7798058777

Registration Link: Linux Classes in Pune!

 

Q2) Why is a shell script needed?

🡺

  1. Shell scripts can be written for a variety of reasons:
  2. Keeping repetitive tasks to a minimum.
  3. Can be used by system administrators for routine backups.
  4. Monitoring the system.
  5. Adding new functions to the shell.
  6. Shell scripting allows you to create your own tools.
  7. System admin can automate daily tasks.

 

Q3) What are Shell variables?

🡺 Shell variables form the core part of a Shell program or script. The variables allow Shell to store and manipulate information within a Shell program. Shell variables are generally stored as string variables.

 

Q4) In shell scripting, what is the significance of the Shebang line?

🡺 It simply provides information regarding the location where the engine is placed. The engine is the one that executes the script. The Shebang line is present at the top of the script and it can be neglected by the users if they want the same.

Q5) What command can be used to test if $a greater than 12?

🡺 The following command is used: [ $a -gt 12 ]

Q6) From where would the read statement read if the following statements were executed?

Code:

exec < file1

    exec < file2

    exec < file3

   read line

🡺 It would not read any files\

Q7) What are interactive and non-interactive shells?

🡺 

Interactive shell: /bin/bash and /bin/sh is interactive shell. It is a non-login shell that gets started from a command line. It first copies the parent environment and then invokes.

Non-Interactive shell: /sbin/nologin shell is non-interactive shell. It is present when the shell script is running and just inherits the parent’s environment.

Q8) Name different commands that are available to check the disk usage.

🡺  The following commands are available to check disk space usage:

  • df – It is used to find out how much space is left on a disk.
  • du – With this command, you can find out how much disk space the specified files and each subdirectory take up.
  • dfspace – Using this command, you can check the amount of free disk space in MB

Q9) In shell scripting, how can you initiate the process of creating a directory within your script?

🡺

When creating a directory in a shell script, you would typically utilise a specific command or method to achieve this task. This action allows you to establish a new directory within the script’s context, facilitating organised data management and file handling processes. 

Q10) How to compare values in bash?

🡺

Six types of comparison operators can be used in bash to compare values. There are two ways to use these operators in bash depending on the data type.  These are mentioned below.

String Comparison Integer Comparison Description
== -eq It is used to check equality
!= -ne It is used to check inequality
< -lt It is used check the first value is less than the second value or not
> -gt It is used check the first value is greater than the second value or not
<= -le It is used check the first value is less than or equal to the second value or not
>= -ge It is used check the first value is greater than or equal to the second value or not

 

Q11) What are the different types of variables used in shell script?

🡺
There are two types of variables used in shell script:

System defined variables: These variables are defined or created by operating system itself.

User defined variables: These variables are defined by system users.

Q12) What are Loops and explain three different methods of loops in brief?

🡺

Loops are the ones, which involve repeating some portion of the program/script either a specified number of times or until a particular condition is being satisfied.

 

For Free Demo classes Call:7798058777

Registration Link: Click Here!

 

 

Q13) How to tell which shell you are in or running?

🡺 We can check it using $echo $0

 

Q14) Differentiate between $@ and $*

🡺

$* = Consider all arguments as single entry

$@ = Consider all arguments as separate entry.

Example: for i in “$@” 

 

Q15) What will be the output of this script?

#!/bin/bash

SHELL=”csh”

 

if [[ “${SHELL}” = “bash” ]]

then

        echo “You seem to like the bash shell.”

elif [[ “${SHELL}” = “csh” ]]

then

        echo “You seem to like the csh shell.”

else

        echo “You don’t seem to like the bash or csh shells.”

fi

🡺

Step 1: vi f1.sh 

Step 2: vi f1.sh 

#!/bin/bash

SHELL=”csh”

 

if [[ “${SHELL}” = “bash” ]]

then

        echo “You seem to like the bash shell.”

elif [[ “${SHELL}” = “csh” ]]

then

        echo “You seem to like the csh shell.”

else

        echo “You don’t seem to like the bash or csh shells.”

fi

Step 3:. /f1.sh 

Step 4: Output are as below:

You seem to like the csh shell.

 

Note: Do visit our blog related to Mostly Asked Interview Questions on Linux

Q16) In what ways does, shell script get input values from a user or terminal?

🡺

By reading command: read –p “Your name” name

By parameters: ./script param1 param2

 

Q17) Is it possible to run multiple scripts at a time? If yes then how?

🡺

To run multiple scripts at a time, we can invoke name of the scripts in another script.

Like script1m script2, can be used in script3

 Q18) How to stop a script in based on a given condition?

Which keyword can be used to stop a script

🡺

Using exit command.

 

For Free Demo classes Call:7798058777

Registration Link: Click Here!

 

Q19) Write a Shell Script to print from 1 to 5 using while loop

🡺

  • The while loop is similar to a for loop and help in executing a block of code multiple times as long as some given condition is satisfied.
  • Where condition is some condition which if satisfied results in the execution of the body of the loop.
  • To come out of the while loop we make the condition fail.
  • To quit the script we can use the exit command.

Code are as below:

Step 1: vi f1.sh 

Step 2: 

#!/bin/bash

#initialise i

i=1

while [ $i -le 5 ]

do

        #echo i

        echo $i

 

        #update i

        i=`expr $i + 1`

done

Step 3: chmod 777 f1.sh 

Step 4: ./f1.sh 

Step 5: Output are as below: ./f1.sh 

1

2

3

4

5

 

Q20) Write a Shell Script to print the following pattern

1

1 3

1 3 5

1 3 5 7

🡺

  • In this below code we use “r” variable to count the rows.
  • “c” variable to count the columns.
  • And we will use “counter” variable to print the number.

Code are as below:

Step 1: vi f2.sh 

Step 2: 

#!/bin/sh

# for the rows

r=1

while [ $r -le 4 ]

do

  # for the output

  count=1

  # for the column

  c=1

 

  while [ $c -le $r ]

  do

   # print the value

   printf “$count “

    # update count

    count=$(( $count + 2 ))

    # update c

    c=$(( $c + 1 ))

  done

  # go to new line

  printf “\n”

  # update r

  r=$(( $r + 1 ))

done

Step 3: chmod 777 f2.sh 

Step 4: ./f2.sh 

Step 5: Output are as below: ./f2.sh 

1 3 

1 3 5 

1 3 5 7

 

Q21) Write a Shell Script to create a function that accepts user name and displays a greetings message.

🡺

Function:

  • A function is a block of code written for a specific task.
  • Functions in Shell are similar to subroutines or procedures in other programming language like C.

Function syntax:

function functionName()

{

   # some code goes here…

}

Whereas,

functionName: is the name of the function.

(): We have the opening and closing parenthesis ().

{and ends at}: The body of the function starts from {and ends at }.

{}: Inside the opening and closing curly brackets {} we have the body of the function.

Function name: We follow the given rules when naming functions.

  • Name must start with letters (a-z or A-Z) or underscore _
  • After that we can use letters (a-z and A-Z), underscore _ and digits (0-9)
  • Don’t put space in the function name
  • Don’t use special keywords like echo, printf etc to name your function.

 

Code are as below:

Step 1: vi f3.sh 

Step 2: 

#!/bin/sh

 

# create a function

function greetings()

{

  echo “Hello World”

}

# call the function

greetings

Step 3: ./f3.sh 

Step 4: Output are as below:

Hello World

For Free Demo classes Call:7798058777

Registration Link: Click Here!

 

Q22) Write a Shell Script to create a function that accepts user name and displays a greetings message

🡺

Passing argument to a function:

We can also pass arguments to a function in shell script and access them using variables like $1, $2, $3… Where, $1 points at the first argument, $2 points at the second argument and so on.

Step 1: vi f4.sh 

Step 2: 

#!/bin/sh

 

# create a function

greetings() {

  echo “Hello $1”

}

 

# call the function

greetings “Yusuf Shakeel”

Step 3: chmod 777 f4.sh

Step 4: ./f4.sh

Step 5: Output are as below:

Hello Yusuf Shakeel

 

Q23) Write a Shell Script to print the following pattern

     #

    ##

   ###

  ####

 #####

######

🡺

Step 1: vi pattern1.sh 

Step 2: 

# Program to print the

# given pattern

 

# Static input for N

N=5

 

# variable used for

# while loop

i=0

j=0

 

while [ $i -le `expr $N – 1` ]

do

    j=0

     

    while [ $j -le `expr $N – 1` ]

    do

        if [ `expr $N – 1` -le `expr $i + $j` ]

        then

          # Print the pattern

          echo -ne “#”

        else

          # Print the spaces required

          echo -ne ” “

        fi

        j=`expr $j + 1`

    done

    # For next line

    echo

              

    i=`expr $i + 1`

done

 

Step 3: chmod 777 pattern1.sh 

Step 4: Output are as below:

      #

   ##

  ###

 ####

#####

 

Q24) Generally, each block in UNIX is how many bytes?

🡺 Each block in UNIX is 1024 bytes.

 

Q25) By default, a new file and a new directory that is being created will have how many links?

🡺 New file contains one link. And a new directory contains two links.

 

Q26) How to find all the available shells in your system?

🡺 We can find all the available shells in our system with $ cat /etc/shells.

Output are as below:

[root@RHCSA-Server2 ~]# cat /etc/shells 

/bin/sh

/bin/bash

/usr/bin/sh

/usr/bin/bash

 

Q27) How many fields are present in a crontab file and what does each field specify?

🡺 The crontab file has six fields. The first five fields tell cron when to execute the command: minute (0-59), hour (0-23), day (1-31), month (1-12), and day of the week (0-6, Sunday = 0).

 

For Free Demo classes Call:7798058777

Registration Link: Linux Course in Pune!

 

Q28) What command needs to be used to take the backup?

🡺 is the command which needs to be used to take the backup. It stands for tape archive. The tar command is mainly used to save and restore files to and from an archive medium tar like tape.

 

Q29) Which command is used to check how many ports are currently being used (listening) on the local machine, and which application is listening on each port?

🡺 To check the listening ports and applications, you can use the 

netstat command: netstat –tupln

 

Q30) Where can you find the following configuration:

“verma ALL=(ALL) ALL”

🡺 Sudoers configuration in /etc/sudoers file.

 

Q31) Which service is used to manipulate incoming and outgoing packets in Linux?

🡺 “iptables” service is used to manipulate incoming and outgoing packets in Linux.

Q32) Which command is used to set the eth0 interface to auto-negotiation on?

🡺 You can use the ethtool command to configure the ethernet card:

ethtool –change eth0 autoneg on.

 

Q33) How can you send a message “Hello Everyone” to everyone who is currently connected to the system?

🡺 You can use the command “wall Hello Everyone”. If you want to send a message to all of the connected users.

 

Q34) Which command is used with gzip for decompression?

🡺 The gzip tool provides another tool gunzip for gzip files decompression. 

 

Q35) How do you tell the named to reload the configuration with the DNS admin tool after you have updated your DNS server configuration?

🡺 You can use the DNS admin tool “rndc” to reload the configuration with – “rndc reload” command.

 

Q36) How would you copy the file “file1.txt” owned by root using secure ftp from 10.1.1.2 on /root/ to your local folder in one command?

🡺 You need to use the scp tool (secure copy over sftp) which allows copying in one line scp root@10.1.1.2:/root/file1.txt ./ 

 

Q37) How can you verify that the file has not been corrupted when you have moved a file from one server to another, but you are not sure that the file has been perfectly moved.

🡺 You have to use the md5sum tool on both servers on the file and match the result, if it is the same, the file has not been corrupted. 

 

Q38) You have a tar file (myFile.tar), how do you convert it to a gzip file on best compression?

🡺 If you need to compress the file with best compression ratio then you need to run the command “gzip -9 myFile.tar” and it will convert myFile.tar file into myFile.tar.gz. file. 

 

Q39) How can you get a view of the calendar of Feb 2024 on a Linux console?

🡺 cal 02 2024. By using this command you can get a view of the month/year calendar. 

 

Q40) You have hundreds of text files in a directory, you want to know in which file you have the string “My String”, how can you do it?

🡺 You can use the command “grep” with regular expression in order to find data in files – grep “My String” *.txt 

 

Q41) How SSH is different than Telnet?

🡺 SSH and Telnet are both communication protocols to manage a remote system, Unlike Telnet which sends the data on clear-text, SSH is the secured version of the telnet, and will require key exchange . 

 

Q42) What should you do when you have an application crashes, but there is no core file created?

🡺 To disable the creation of the core dump file, make sure that the ulimit -c is not set to 0.

 

Q43) What tool would you use if you want to benchmark your apache service that holds www.google.com using 5 concurrent requests over 20 overall requests?

🡺 You can use the ab (apache benchmarking) tool on localhost – ab Http://google.com -n 20 -c 5.

 

Q44) Which control script is used to stop the Apache HTTPD service?

🡺 You can use “apachectl” control script for controlling apache. And you can use “apachectl stop” to stop the apache HTTPD service.  

 

Q45) What is the use of a pipe operator? How to execute multiple commands in one line?

🡺 The pipe operator is used for one by one execution of command but commands should not be dependent on each other.

Q46) What are the two files of crontab command?

🡺 cron.allow which decides the users need to be permitted for using the crontab command.

cron.deny which decides the users need to be prevented from using the crontab command

Q47) How can I set the default permission to all users on every file which is created in the current shell?

🡺 umask 777

Q48) How to find the total disk space used by a specific user?

🡺 du -s /home/username

Q49) I want to create a directory such that anyone in the group can create a file and access any person’s file in it but none should be able to delete a file other than the one created by himself.

🡺 We can create the directory giving read and execute access to everyone in the group and setting its sticky bit “t” on as follows: 

mkdir direc1

chmod g+wx direc1

chmod +t direc1

Q50) how to find process name from process ID?

🡺 “ps –p pid” command used to find the process name.

 

To explore more do visit: Click Here

 

Author:-

Gandhar Bodas

Call the Trainer and Book your free demo Class For Linux Call now!!!
| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

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

*
*