Shell Scripting Interview Questions & Answers - GUIDE To CRACK
Unix Shell Scripting Interview Questions and Answers

Shell Scripting Interview Questions & Answers – GUIDE To CRACK

Last updated on 03rd Jun 2020, Blog, Interview Questions

About author

RamaKrishnan (Sr Technical Architect )

High level Domain Expert in TOP MNCs with 12+ Years of Experience. Also, Handled Around 36+ Projects and Shared his Knowledge by Writing these Blogs for us.

(5.0) | 15212 Ratings 3318

A Unix shell is a command-line interpreter or shell that provides a command line user interface for a Unix-like operating system. The shell is both an interactive command language and a scripting language, and is used by the operating system to control the execution of the system using shell scripts.

1. What Is Shell Script And Why It Is Required?

Ans:

A Shell Script is a text file that contains one or more commands. As a system administrator we often need to issue a number of commands to accomplish the task, we can add these all commands together in a text file (Shell Script) to complete daily routine tasks.

2. What Is The Default Login Shell And How To Change Default Login Shell For A Specific User?

Ans:

In Linux like Operating system “/bin/bash” is the default login shell which is assigned while user creation. We can change the default shell using the “chsh” command.

Example is shown below:

  • # chsh <username> -s <new_default_shell>
  • # chsh linuxtechi -s /bin/sh

3. What Are The Different Types Of Variables Used In A Shell Script?

Ans:

In a shell script we can use two types of variables:

  • System defined variables
  • User defined variables

System defined variables are defined or created by the Operating System (Linux) itself. These variables are generally defined in Capital Letters and can be viewed by the “set” command.

User defined variables are created or defined by system users and the values of variables can be viewed by using the command “echo $<Name_of_Variable>”.

4. How To Redirect Both Standard Output And Standard Error To The Same Location?

Ans:

There two methods to redirect std output and std error to the same location:

Method:1

  • 2>&1 (# ls /usr/share/doc > out.txt 2>&1 )

Method:2

  • &> (# ls /usr/share/doc &> out.txt )

5. What Is The Syntax Of “Nested If Statement” In Shell Scripting?

Ans:

Basic Syntax is shown below:

  • if [ Condition ]
  • then
  • command1
  • command2
  • …..
  • else
  • if [ condition ]
  • then
  • command1
  • command2
  • ….
  • else
  • command1
  • command2
  • …..
  • fi
  • fi

6. What Is The Use Of “$?” Sign In Shell Script?

Ans:

While writing a shell script, if you want to check whether the previous command is executed successfully or not, then we can use “$?” with an if statement to check the exit status of the previous command.

Basic example is shown below:

  • root@localhost:~# ls /usr/bin/shar
  • /usr/bin/shar
  • root@localhost:~# echo $
  • 0
  • If exit status is 0 , then command is executed successfully
  • root@localhost:~# ls /usr/bin/share
  • ls: cannot access /usr/bin/share: No such file or directory
  • root@localhost:~# echo $
  • 2

If the exit status is other than 0, then we can say command is not executed successfully.

7. How To Compare Numbers In Linux Shell Scripting?

Ans:

Test command is used to compare numbers in if-then statements.

Example is shown below:

  • #! /bin/bash
  • x=10
  • y=20
  • if [ $x -gt $y ]
  • then
  • echo “x is greater than y”
  • else
  • echo “y is greater than x”
  • #! /bin/bash
  • x=10
  • y=20
  • if [ $x -gt $y ]
  • then
  • echo “x is greater than y”
  • else
  • echo “y is greater than x”
  • #! /bin/bash
  • x=10
  • y=20
  • if [ $x -gt $y ]
  • then
  • echo “x is greater than y”
  • else
  • echo “y is greater than x”
  • fi

8. What Is The Use Of Break Command?

Ans:

The break command is a simple way to escape out of a loop in progress. We can use the break command to exit out from any loop, including while and until loops.

9. What Is The Use Of Continue Command In Shell Scripting?

Ans:

The continue command is identical to break command except it causes the present iteration of the loop to exit, instead of the entire loop. Continue command is useful in some scenarios where error has occurred but we still want to execute the next commands of the loop.

10. What Is The Basic Syntax Of While Loop In Shell Scripting?

Ans:

Like the for loop, the while loop repeats its block of commands a number of times. Unlike the for loop, however, the while loop iterates until its while condition is no longer true.

The basic syntax is :

  • while [ test_condition ]
  • do
  • commands…
  • done

11. How To Make A Shell Script Executable?

Ans:

Using the chmod command we can make a shell script executable.

Example is shown below :

  • # chmod a+x myscript.sh

12. What Is The Use Of “#!/bin/bash” ?

Ans:

 #!/bin/bash is the first of a shell script , known as shebang , where # symbol is called hash and ‘!’ is called as bang. It shows that command to be executed via /bin/bash.

13. How To Debug A Shell Script?

Ans:

A shell script can be debugged if we execute the script with ‘-x’ option ( sh -x myscript.sh). Another way to debug a shell script is by using the ‘-nv’ option (sh -nv myscript.sh).

14. How Compare The Strings In Shell Script?

Ans:

Test command is used to compare the text strings. The test command compares text strings by comparing each character in each string.

15. What Are The Special Variables Set By Bourne Shell For Command Line Arguments?

Ans:

Special Variables: Holds

  • $0: Name of the Script from the command line
  • $1: First Command-line argument
  • $2: Second Command-line argument
  • …..
  • …….
  • $9: Ninth Command line argument
  • $#: Number of Command line arguments
  • $*: All Command-line arguments, separated with spaces

16. How To Test Files In A Shell Script?

Ans:

Test command is used to perform different tests on the files. Basic test are listed below:

Test: Usage

  • -d file_name: Returns true if the file exists and is a directory.
  • -e file_name: Returns true if the file exists.
  • -f file_name: Returns true if the file exists and is a regular file.
  • -r file_name: Returns true if the file exists and has read permissions.
  • -s file_name: Returns true if the file exists and is not empty.
  • -w file_name: Returns true if the file exists and has write permissions.
  • x file_name: Returns true if the file exists and has execute permissions.

17. How To Put Comments In Your Shell Script?

Ans:

Comments are messages to yourself and to other users that describe what a script is supposed to do and how it works. To put comments in your script, start each comment line with a hash sign (#).

Example is shown below:

  • #!/bin/bash
  • # This is a command
  • echo “I am logged in as $USER”

18. How To Get Input From The Terminal For Shell Script?

Ans:

‘read’ command reads in data from the terminal (using keyboard). The read command takes in whatever the user types and places the text into the variable you name.

Example is shown below:

  • # vi /tmp/test.sh
  • #!/bin/bash
  • echo ‘Please enter your name’
  • read name
  • echo “My Name is $name”
  • # ./test.sh

Please enter your name

LinuxTechi

My Name is LinuxTechi

19. How To Unset Or De-assign Variables?

Ans:

‘unset’ command is used to de-assign or unset a variable.

Syntax is shown below:

  • # unset <Name_of_Variable>

20. How To Perform Arithmetic Operation?

Ans:

There are two ways to perform arithmetic operations:

  1. Using expr command (# expr 5 + 2).
  2. Using a dollar sign and square brackets ( $[ operation ] ) Example : test=$[16 + 4] ; test=$[16 + 4].

    Subscribe For Free Demo

    21. Basic Syntax Of Do-while Statement?

    Ans:

    The do-while statement is similar to the while statement but performs the statements before checking the condition statement.

    The following is the format for the do-while statement:

    •  do
    •  {
    •  statements
    •  } while (condition)

    22. How To Define Functions In Shell Scripting?

    Ans:

    A function is simply a block of code with a name. When we give a name to a block of code, we can then call that name in our script, and that block will be executed.

    Example is shown below: 

    • $ disk usage () { df -h ; }

    23. How To Use Bc (bash Calculator) In A Shell Script?

    Ans:

    Use the below Syntax to use bc in shell script.

    • Variable=`echo “options; expression” | bc`.

    24. How to pass arguments to a script ?

    Ans:

     ./script argument

    Example : Script will show filename

    • ./show.sh file1.txt
    • cat show.sh
    • #!/bin/bash

    cat $1

    25.  How to use arguments in a script ?

    Ans:

    First argument: $1,

    Second argument : $2

    Example : Script will copy file (arg1) to destination (arg2)

    • ./copy.sh file1.txt /tmp/
    • cat copy.sh
    • #!/bin/bash
    • cp $1 $2

    26. How to get 2nd element from each line from a file, if first equal FIND

    Ans:

    • awk ‘{ if ($1 == “FIND”) print $2}’

    27. How to debug bash script

    Ans:

    Add -xv to #!/bin/bash

    Example

    • #!/bin/bash –xv

    28. Give an example of how to write a function ?

    Ans:

    • function example {
    • echo “Hello world!”
    • }

    29. How to add string to string ?

    Ans:

    • V1=”Hello”
    • V2=”World”
    • let V3=$V1+$V2
    • echo $V3

    Output

    Hello+World

    30. How to add two integers ?

    Ans:

    • V1=1
    • V2=2
    • V3=$V1+$V2
    • echo $V3

    Output

    3

    Remember you need to add “let” to line V3=$V1+$V2

    then echo $V3 will give 3

    if without let , then it will be

    echo $V3 will give 1+2

    31. How to check if a file exists on a filesystem ?

    Ans:

    • if [ -f /var/log/messages ] then
    • echo “File exists”
    • fi

    32. Write down syntax for all loops in shell scripting ?

    Ans:

    for loop :

    • for i in $( ls ); do
    • echo item: $i
    • done

    while loop :

    • #!/bin/bash
    • COUNTER=0
    • while [ $COUNTER -lt 10 ]; do
    • echo The counter is $COUNTER
    • let COUNTER=COUNTER+1
    • done

    until loop :

    • #!/bin/bash
    • COUNTER=20
    • until [ $COUNTER -lt 10 ]; do
    • echo COUNTER $COUNTER
    • let COUNTER-=1
    • done

    33. What it means by #!/bin/sh or #!/bin/bash at the beginning of every script ?

    Ans:

    That line tells which shell to use. #!/bin/bash script to execute using /bin/bash. In case of python script there there will be #!/usr/bin/python

    34. What does the command “export” do ?

    Ans:

    Makes variable public in subshells

    35.  How to run a script in the background ?

    Ans:

    add “&” to the end of script

    Course Curriculum

    Best Advanced Unix Shell Scripting Training from MNC Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    36. What does “chmod 500 script” do ?

    Ans:

    Makes script executable for script owner

    37. What “>” do ?

    Ans:

    Redirects output stream to file or another stream.

    38. What difference between & and &&

    Ans:

    & – we using it when want to put script to background

    && – when we wand to execute command/script if first script was finished successfully

    39. When we need “if” before [ condition ] ?

    Ans:

    When we need to run several commands if condition meets.

    40. What would be the output of the command: name=John && echo ‘My name is $name’

    Ans:

    My name is $name

    41. What difference between ‘ and ” quotes ?

    Ans:

    • we use it when do not want to evaluate variables to the values
    • all variables will be evaluated and its values will be assigned instead.

    42. How to redirect stdout and stderr streams to log.txt file from script inside ?

    Ans:

    Add “exec >log.txt 2>&1” as the first command in the script

    43. How to get part of a string variable with echo command only ?

    Ans:

    echo ${variable:x:y}

    x – start position

    y – length

    example:

    • variable=”My name is Petras, and I am a developer.”
    • echo ${variable:11:6} # will display Petras

    44. How to get home_dir with echo command only if string variable=”User:123:321:/home/dir” is given ?

    Ans:

    • echo ${variable#*:*:*:}
    • or
    • echo ${variable##*:}

    45. How to get “User” from the string above ?

    Ans:

    • echo ${variable%:*:*:*}
    • or
    • echo ${variable%%:*}

    46. How to list users whose UID is less than 100 (awk) ?

    Ans:

    • awk -F: ‘$3<100’ /etc/passwd

    47. Write the program which counts unique primary groups for users and displays count and group name only

    Ans:

    • cat /etc/passwd|cut -d: -f4|sort|uniq -c|while read c g
    • do
    • { echo $c; grep :$g: /etc/group|cut -d: -f1;}|xargs -n 2
    • done

    48.  How to get variable length ?

    Ans:

    • ${#variable}

    49. How to print the last 5 characters of a variable ?

    Ans:

    • echo ${variable: -5}

    50. What difference between ${variable:-10} and ${variable: -10} ?

    Ans:

    • ${variable:-10} – gives 10 if variable was not assigned before
    • ${variable: -10} – gives last 10 symbols of variable

    51. How to substitute part of string with echo command only ?

    Ans:

    • echo ${variable//pattern/replacement}

    52. Which command replaces string to uppercase ?

    Ans:

    • tr ‘[:lower:]’ ‘[:upper:]’

    53. How to count local accounts ?

    Ans:

    • wc -l /etc/passwd|cut -d” ” -f1

    or

    • cat /etc/passwd|wc -l

    54. How to count words in a string without wc command ?

    Ans:

    • set ${string}
    • echo $#

    55. Which one is correct: “export $variable” or “export variable” ?

    Ans:

    export variable

    Course Curriculum

    Enroll in Unix Shell Scripting Certification Course By Experts Trainers

    Weekday / Weekend BatchesSee Batch Details

    56. How to list files where the second letter is a or b ?

    Ans:

    • ls -d ?[ab]*

    57. How to add integers a to b and assign to c ?

    Ans:

    • c=$((a+b))

    or

    • c=`expr $a + $b`

    or

    • c=`echo “$a+$b”|bc`

    58. How to remove all spaces from the string ?

    Ans:

    • echo $string|tr -d ” “

    59. Rewrite the command to print the sentence and convert the variable to plural: item=”car”; echo “I like $item” ?

    Ans:

    • item=”car”; echo “I like ${item}s”

    60. Write the command which will print numbers from 0 to 100 and display every third (0 3 6 9 …) ?

    Ans:

    • for i in {0..100..3}; do echo $i; done

    or

    • for (( i=0; i<=100; i=i+3 )); do echo “Welcome $i times”; done

    61. How to print all arguments provided to the script ?

    Ans:

    • echo $*

    or

    • echo $@

    62. What difference between [ $a == $b ] and [ $a -eq $b ]

    Ans:

    • [ $a == $b ] – should be used for string comparison
    • [ $a -eq $b ] – should be used for number tests

    63. What difference between = and ==

    Ans:

    • = – we using to assign value to variable
    • == – we using for string comparison

    64. Write the command to test if $a greater than 12 ?

    Ans:

    • [ $a -gt 12 ]

    65. Write the command to test if $b less or equal 12 ?

    Ans:

    • [ $b -le 12 ]

    66. How to check if a string begins with “abc” letters ?

    Ans:

    • [[ $string == abc* ]]

    67. What difference between [[ $string == abc* ]] and [[ $string == “abc*” ]]

    Ans:

    • [[ $string == abc* ]] – will check if string begins with abc letters
    • [[ $string == “abc*” ]] – will check if string is equal exactly to abc*

    68. How to list usernames which starts with ab or xy ?

    Ans:

    • egrep “^ab|^xy” /etc/passwd|cut -d: -f1

    69. What $! means in bash ?

    Ans:

    Most recent background command PID

    70. What $? means ?

    Ans:

    Most recent foreground exit status.

    Unix Shell Scripting Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    71. What difference between $* and $@

    Ans:

    • $* – gives all passed arguments to the script as a single string
    • $@ – gives all passed arguments to the script as a delimited list. Delimiter $IFS

    72. How to define array in bash ?

    Ans:

    • array=(“Hi” “my” “name” “is”)

    73. How to print the first array element ?

    Ans:

    • echo ${array[0]}

    74. How to print all array elements ?

    Ans:

    • echo ${array[@]}

    75. How to print all array indexes ?

    Ans:

    • echo ${!array[@]}

    76. How to remove the array element with id 2 ?

    Ans:

    • unset array[2]

    77. How to add a new array element with id 333 ?

    Ans:

    • array[333]=”New_element”

    87. How does a shell script get input values ?

    Ans:

    a) via parameters

    • ./script param1 param2

    b) via read command

    • read -p “Destination backup Server : ” desthost

    79.How can we use the “expect” command in a script ?

    Ans:

    • /usr/bin/expect << EOD
    • spawn rsync -ar ${line} ${desthost}:${destpath}
    • expect “*?assword:*”
    • send “${password}\r”
    • expect eof
    • EOD

    80. What is Shell Scripting and why is it important?

    Ans:

    Shell acts as a link between you and the operating system, allowing you to give commands to the computer. Shell Scripting is important because you can use it to execute a sequence of commands in bulk rather than one instruction at a time.

    81. What are the most common Shell types?

    Ans:

    There are 4 major Shell types: Bourne Shell (sh), C Shell (csh), Korn Shell (ksh) and Bourne Again Shell (bash).

    Of this, the (bash) type is the most frequently used.

    82. How do you begin and end execution of a Shell Script?

    Ans:

    You can make the script executable through the UNIX chmod command.

    To terminate the program, you can use the ‘fi’ command.

    83. What are hard links and soft links?

    Ans:

    ‘Links’ are shortcuts that you can create on Linux.

    Soft links can be kept on different file systems and are linked to the file name. Hard links, however, are linked to the inode of your file and need to be kept on the same file system as your file.

    84. What is a zombie process?

    Ans:

    A zombie process is a program that is no longer functional but still hasn’t had its exit status picked up by the [aren’t process. This way it still has its process id entry in the table.

    85. How many kernels and shells come with a UNIX OS?

    Ans:

    Typically, you can have about 280 shell scripts that are available with the UNIX OS, while one kernel is available in the environment.

    86. Can shell scripting be used for all situations?

    Ans:

    It is recommended that you avoid shell scripting in situations that require a high degree of productivity, complex writing tasks or when various software tools are required.

    87. What is the default file permission and how can we modify it?

    Ans:

    When you create a file, its default permission is set at 666 (rw-rw-rw).

    You can modify this setting using the command umask.

    88. What is the function of shell variables?

    Ans:

    You can use shell variables to store and modify data within a shell program. They are the main component of shell scripting.

    89. What are the types of shell variables in UNIX OS?

    Ans:

    You can use two main types of variables.

    a. UNIX Defined or System Variables: These are standard variables that are defined in capital letters.

    b. User Defined Variables: these are variables that you can define and are usually in lower case letters.

    90 . How can you debug a shell script problem?

    Ans:

    You can debug your shell script in many ways.

    One way is to insert a debug statement within the script that will output data that can help you pinpoint the problem.

    You can also use the ‘set-x’ statement to help the debugging process.

    91. What is the difference in using break and continue statements?

    Ans:

    Within a loop script, you can use the break statement to completely terminate the entire loop. However, using the continue statement will only terminate your current iteration, while the loop script will continue on to the next iteration.

    92. What do shell scripts rely on?

    Ans:

    They rely on the fact that commands can be accepted from both the keyboard and the files.

    93. How can variables be manipulated?

    Ans:

    You can use two common commands to manipulate variables.

    ‘Readonly’ helps you set a particular value for the variable and makes it unchangeable.

    ‘Unset’ command can be used to erase a variable’s previous value and set a new one.

    94. What are the types of blocks in a file system?

    Ans:

    In a file system there are four blocks:

    a. Boot Block: tells you the state of your file systems.

    b. Super Block: represent the beginning of a file system.

    c. Inode Table: stores information related to files.

    d. Data Block: contains actual files and their content.

    95. How to put comments in your bash shell script ?

    Ans:

    Comments are the messages to yourself and for other users that describe what a script is supposed to do and how its works.To put comments in your script, start each comment line with a hash sign (#) . Example is shown below :

    • #!/bin/bash
    • # This is a command
    • echo “I am logged in as $USER”

    96. How to get input from the terminal for shell script ?

    Ans:

    ‘read’ command reads in data from the terminal (using keyboard). The read command takes in whatever the user types and places the text into the variable you name. Example is shown below :

    • # vi /tmp/test.sh
    • #!/bin/bash
    • echo ‘Please enter your name’
    • read name
    • echo “My Name is $name”
    • # ./test.sh

    Please enter your name

    LinuxTechi

    My Name is LinuxTechi

    97. How to unset or de-assign variables in Linux ?

    Ans:

    ‘unset’ command is used to de-assign or unset a variable. Syntax is shown below :

    • # unset <Name_of_Variable>

    98. How to perform arithmetic operations in Linux ?

    Ans:

    There are two ways to perform arithmetic operations :

    1. Using expr command (# expr 5 + 2 )

    2. using a dollar sign and square brackets ( $[ operation ] )

    Example :

    • test=$[16 + 4] ; test=$[16 + 4]

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free