• Articles
  • Tutorials
  • Interview Questions

Top Shell Scripting Interview Questions for 2024

Top Shell Scripting Interview Questions for 2024

CTA

Shell scripting is crucial for automating tasks, managing system configurations, and enhancing efficiency. It streamlines repetitive operations, reduces human error, accelerates complex tasks, and makes it indispensable in modern IT environments. Shell scripting entails composing a sequence of UNIX commands within a plain text document, designed to fulfill specific objectives.

Preparing for a shell scripting interview involves mastering a range of topics, including Unix and Linux shell scripting interview questions, both basic and advanced. To excel, experienced candidates must also delve into detailed shell scripting interview questions and answers. Comprehensive knowledge of these areas ensures a confident and successful performance during the interview process.

Listed below are several commonly asked interview questions and answers regarding shell scripting:

1. What is a shell script?
2. How is a shell script written?
3. Which command is used to execute a shell file?
4. Name the most commonly used shells on a typical Linux system.
5. Explain the difference between single quotes (‘) and double quotes (“)
6. What is the purpose of the case statement in shell scripting?
7. Define shell variable.
8. What is the difference between $$ and $!?
9. What is a kernel?
10. How do you give a variable in a shell script a value?

Table of content

Basic Shell Scripting Interview Questions for Freshers

1. What is a shell script?

A file containing a series of commands that are translated and carried out by a shell interpreter is known as a shell script. It enables task automation and command execution on an operating system with a Unix foundation.

2. How is a shell script written?

You must create a plain text file with the extension <file-name>.sh to construct a shell script. The script can be written using any text editor, such as vi, nano, or cat.

3. Which command is used to execute a shell file?

To execute a shell script (a text file containing shell commands), you typically use
./script.sh extension.
Replace “script.sh” with the actual name of your shell script.
Ensure the script has executable permissions set using the following chmod command if needed:
chmod +x script.sh
This makes the script executable, allowing you to run it using the ./ notation.

4. Name the most commonly used shells on a typical Linux system.

Linux shells primarily fall into two categories: C-shell and Bourne shell. Their derivatives are as follows:

  • C-shell: TENEX C-Shell, Z-Shell
  • Bourne shell: Korn Shell, Bourne-Again Shell, POSIX Shell

5. Explain the difference between single quotes (') and double quotes (

Here are the major differences between single quotes (‘) and double quotes (“) in shell scripting:

Parameter Single Quotes (‘) Double Quotes (“)
Variable Substitution No variable substitution occurs inside single quotes. Variable substitution occurs inside double quotes.
Escaping Special Characters Special characters within single quotes are treated as literal characters and not escaped. Special characters within double quotes can be escaped using a backslash ().
Command Substitution Command substitution is not allowed within single quotes. Command substitution (e.g., $(command)) is supported within double quotes.
Literal String Preservation Text enclosed in single quotes is treated as a literal string, preserving spaces and formatting. Text enclosed in double quotes is parsed, allowing variables and special characters to be interpreted.
Nested Quotes Nested single quotes within single quotes are not permitted. Nested double quotes within double quotes are permitted.
Word Splitting Word splitting does not occur inside single quotes. Word splitting occurs inside double quotes, making it suitable for handling strings with spaces.

6. What is the purpose of the case statement in shell scripting?

The purpose of the case statement in shell scripting is to provide a structured and efficient way to perform conditional branching based on pattern matching. It simplifies decision-making by allowing the script to execute different code blocks for specific pattern matches, enhancing code readability.

7. Define shell variable.

A shell variable forms the core of a shell script or program. The variable enables the shell program to handle and manipulate stored information. It is generally stored as a string variable.

8. What is the difference between $$ and $!?

$$ and $! are both special variables in Unix-like operating systems$$ and $!
$$: It represents the process ID (PID) of the currently executing shell or script.d .when you want to create temporary files with unique names to avoid naming conflicts.
$!: It represents the PID of the last background process that was executed in the background using the & operator. It tracks background processes

9. What is a kernel?

The kernel is a fundamental computer program within an operating system, responsible for overseeing and coordinating the operations of the computer and its hardware.

10. How do you give a variable in a shell script a value?

The variable_name=value format is used to assign values to variables in shell scripts. As an illustration, name=”John” gives the variable “name” the value “John”.

11. How do you use conditional statements in a shell script?

Conditional statements in shell scripting are typically made using the “if” statement. It follows the syntax if [ condition ]; then… fi. The “if” block commands are executed if the condition is true.

12. How do you read input from the user in a shell script?

In a shell script, the “read” command enables the user to capture input. It facilitates prompting the user for information and storing their response in a variable.

13. How do you create a loop in a shell script?

Shell scripts can use loops such as the “for” and “while” loops. The “for” loop is used to iterate over a sequence of values, whereas the “while” loop is used to repeat commands as long as a certain condition is true.

14. Mention some limitations of shell scripting.

Shell scripting has the following disadvantages:

  • Errors are frequent and costly; a single error can alter the command.  
  • The execution speed is slow. 
  • Bugs or inadequacies are in the language’s syntax or implementation.  
  • Large, complex tasks aren’t well suited to it.  
  • Contrary to other scripting languages, it provides a minimal data structure.   

15. What are is the absolute and relative paths?

An absolute path provides the full file or directory location from the root directory, starting with / in Unix or a drive letter in Windows. A relative path specifies a location in relation to the current working directory, making it shorter and context-dependent.

16. Elucidate the term shebang line.

The term shebang line in shell scripting refers to the first line of a script that begins with #! followed by the path to the interpreter, such as /bin/bash. It specifies the interpreter to be used for executing the script. This line is crucial as it instructs the system on how to interpret and run the script, ensuring compatibility and proper execution.

17. What are the various stages of the Linux process?

In Linux, a process goes through several stages during its lifecycle:
Creation: A process is created when a program is executed.
Ready: The process is ready to run but waiting for CPU time.
Running: The process is actively using the CPU.
Blocked: The process is waiting for a specific event, such as I/O, to complete.
Terminated: The process has completed its execution or was forcibly terminated.

Shell Scripting Programming Interview Questions for Experienced

18. How will you find the total number of shells available in your system?

To determine the total number of shells available in a system through shell scripting, you can employ the following command: cat /etc/shells | wc -l. This command reads the /etc/shells file and uses the wc command to count the lines, which correspond to the available shells. Executing this command in your terminal will provide you with the desired information regarding the total number of shells available.

19. Define control instructions.

Control instructions in shell scripting are commands that dictate the flow and logic of a script. They include conditional statements (if-else), loops (for, while), and case statements, enabling precise program control. These instructions facilitate decision-making and repetitive tasks, enhancing script functionality and efficiency. Mastering control instructions is essential for effective shell scripting, empowering users to automate processes and manage data effectively.

20. What is LILO?

LILO (Linux Loader) is a legacy boot loader used in Linux systems. It manages the boot process by loading the Linux kernel into memory during system startup. However, it has been largely replaced by GRUB (GRand Unified Bootloader), which offers more features and flexibility in handling multiple operating systems and file systems.

21. What do you mean by positional parameters in shell scripting?

Positional parameters in shell scripting refer to variables that hold values passed to a script or function as command-line arguments. They are denoted by numbers, with $1 representing the first argument, $2 the second, and so on. These parameters enable dynamic input processing, enhancing script flexibility and functionality. Understanding positional parameters is fundamental for effective shell script development.

22. How do you read input from a file line by line in a shell script?

You can use a while loop with the read command to read input from a file line by line. For example:

while IFS= read -r line; do
    # Process each line here
done < input.txt

23. How do you handle errors and exceptions in a shell script?

You can use the set -e option at the beginning of the script to exit immediately if any command returns a non-zero status (indicating an error). Additionally, you can use the trap command to catch and handle specific signals or errors within the script.

24. How do you redirect the output of a command to a file and display it on the terminal simultaneously?

You can use the tee command to achieve this. For example:

command | tee output.txt

Get 100% Hike!

Master Most in Demand Skills Now!

25. How do you compare two strings in a shell script?

String comparison can be made using the double square brackets ([[ ]]) and the == operator. For example:

if [[ $str1 == $str2 ]]; then
    # Strings are equal
fi

26. How do you schedule a shell script to run at a specific time using Cron?

You can schedule a shell script using the crontab command. By editing the crontab file (crontab -e), you can specify the desired time and frequency for the script to run.

27. What is the difference between $@ and $*?

$* treats a group of positional arguments as one complete string, while $@ treats each quoted argument as an individual argument.

28. How do you handle input validation and error checking in a shell script?

You can use conditional statements (if and case) to validate input and check for errors. You can perform error handling and exit the script if necessary by using return codes ($?) and conditional checks.

29. How do you create and use environment variables in a shell script?

By assigning a value to a variable, you can create environment variables. For instance,

MY_VARIABLE="Hello, World!"
export MY_VARIABLE

30. How do you count the number of occurrences of a specific word in a file using shell scripting?

You can use the grep command with the -c option to count the occurrences of a specific word in a file.

31. How do you perform arithmetic calculations in shell scripting?

Shell scripting supports arithmetic calculations using the expr command or double parentheses (( )) for arithmetic expansion. For example,

result=$(expr 2 + 2)
echo $result  # Outputs 4

result=$((2 + 2))
echo $result  # Outputs 4

32. What are CLIand GUI?

CLI (Command Line Interface):

  • Text-based interface.
  • Efficient for experienced users and scripting.
  • Common in Unix-like systems.
  • Requires knowledge of specific commands.GUI (Graphical User Interface):
    • Visual interface with icons and windows.
    • User-friendly and suitable for beginners.
    • Common in Windows, macOS, and desktop applications.
    • Reduces the need for memorizing commands.

33. How will you will define whether the given link is hard or soft?

In shell scripting, the categorization of a given link as hard or soft typically pertains to determining whether the link is symbolic or represents a physical file or directory. This can be accomplished using the ‘test’ command with the ‘-h’ flag, which returns true for symbolic links (soft) and false for actual files or directories (hard). Such distinctions aids in effective file management and scripting logic.

34. What are the different types of variables in shell scripting?

In shell scripting, there are three primary types of variables:
Local Variables: These are defined within a script and are only accessible within the script. Example: count=5.

Environment Variables: These are available system-wide and can be accessed by any script or program. Example: PATH=”/usr/bin:/usr/local/bin”
Shell Variables: These are predefined by the shell and hold system information.
Example:

$HOME (user's home directory).

These variable types serve different purposes and scopes in shell scripting.

35. What is the significance of $#?

The significance of $# in shell scripting is that it represents the number of arguments passed to a script or function. It helps scriptwriters determine the count of positional parameters (arguments) provided when the script is executed. This information can be crucial for creating conditional logic based on the number of arguments or for iterating through and processing them within the script.

36. Explain Crontab?

Crontab is a Unix-based time scheduler for automating repetitive tasks. Users create “cron jobs” by specifying commands and defining when they should run based on a time schedule (minute, hour, day, month, day of the week). It allows users to automate tasks like backups, updates, and scripts at specified intervals. Each user can have their own crontab, and they can edit it using crontab -e. Crontab simplifies system maintenance and task automation on Unix-like systems.

Advanced Shell Scripting Interview Questions

37. Name two files of the crontab command.

The two crontab command files are as follows:

  • cron. deny: These files determine which user or users should be blocked from using the crontab command.
  • cron. allow: These files determine which user or users should be granted permission to use the crontab command.

38. How do you handle and process command-line options in a shell script?

Command-line options can be handled using the getopts command or manually parsing the arguments. The getopts command provides a convenient way to specify and process options and their arguments.

39. How do you securely handle sensitive information (like passwords) in a shell script?

Sensitive information can be stored in environment variables or separate configuration files. You can restrict access to these files using proper file permissions and use tools like OpenSSL to encrypt or decrypt sensitive data.

40. How do you work with arrays in a shell script?

Arrays can be declared and accessed using square brackets and indexes. For example,

myarray=("apple" "banana" "cherry")
echo "${myarray[0]}"  # Outputs "apple"

41. How do you calculate the execution time of a command or script in a shell script?

You can use the time command to measure the execution time of a command or script. For example,

time ./myscript.sh

42. How do you process and manipulate text using regular expressions in a shell script?

You can use the grep, sed, or awk commands with regular expressions to process and manipulate text in a shell script. Regular expressions provide powerful pattern-matching capabilities.

43. What is the alternative to if-else if-else statements in bash?

An alternative to an if-else if-else statement is a case statement. Its syntax differs from the switch case. The ‘case’ block is closed by ‘esac,’ and no break statement is used.

Syntax:

case  in
Match pattern one) commands;
Match pattern two) commands;
esac

44. How do you read and parse CSV or delimited files in a shell script?

You can use the awk command with the appropriate field separator (-F) to parse CSV or delimited files. Alternatively, the cut or read command can extract specific columns.

45. How do you handle concurrent processes or parallel execution in a shell script?

Concurrent processes or parallel execution can be achieved using tools like xargs, parallel, or background processes, and job control operators (&, wait).

46. How do you debug shell scripts effectively?

Effective debugging can be done using the set -x option to enable debugging mode, inserting echo statements to print intermediate values, using the trap command to catch and handle signals, and analyzing log files or error output.

47. Differentiate between the grep and find commands.

Parameter grep (Global Regular Expression Print) find
Functionality Searches for patterns within the content of files. Searches for files and directories in the file system hierarchy.
File Content Focuses on searching within file contents, making it suitable for text-based searches. Concentrates on locating files and directories based on metadata and attributes.
Output Displays lines containing matched patterns within files. Prints the paths of files and directories that meet specified criteria.
Usage grep [options] pattern [file…] is used for text searches. find [path] [expression] is employed for file and directory searches.
Examples grep -r “keyword” /path/to/search searches for “keyword” in files under the specified directory. find /path/to/search -name “*.txt” locates all “.txt” files under the given path.

48. How do you use pipe commands in shell scripting?

To utilize pipe commands in shell scripting, use the ‘|’ symbol to link multiple commands. This allows the output of one command to serve as the input for the next. For example, ‘command1 | command2’ directs the output of ‘command1’ as input to ‘command2’. This powerful technique streamlines tasks, enhances efficiency, and enables complex data processing in shell scripts, making it a valuable tool for system administrators and developers.

49. Distinguish between the two most frequently employed shells in the Linux sSystem.

There are mainly two kinds of Linux shells: C shell and Bourne shell.

Aspect C Shell (csh) Bourne Shell (sh)
Syntax More C-like syntax with command history and tab completion Traditional and straightforward syntax
Scripting Language Primarily used for interactive tasks; limited scripting capabilities Designed for scripting with greater versatility
Control Structures Supports ‘foreach’ and ‘while’ loops Offers ‘if-then-else’ statements and ‘for’ loops
Job Control Robust job control for managing processes interactively Supports job control but less interactive

50. Differentiate between interactive and non-interactive shells.

Parameter Interactive Non-Interactive
Definition Involves real-time, two-way communication where the system responds immediately to user input. Operates without real-time interaction, often following predefined instructions or scripts.
User Engagement Requires active user participation and responses during the interaction. Requires minimal or no user input once initiated.
Response Time Provides immediate responses to user actions, enhancing user engagement and control. Executes predefined tasks without expecting immediate user input, making it more automated.
Examples Video conferencing, live chat support, video games, and virtual assistants that respond to voice commands. Batch processing, automated data analysis, and scheduled tasks like backups or system maintenance.

51. What is the purpose of sed command and awk command?

Parameter sed (Stream Editor) awk (Text Processing Tool)
Usage Text manipulation in a linear, non-interactive manner Text processing with pattern scanning and processing
Functionality Primarily used for substitution, deletion, insertion, and more based on patterns More versatile, as it can perform complex text processing, including pattern matching, text extraction, and mathematical operations
Variables Limited variable support for simple tasks Supports variables and arrays for complex data manipulation and storage
Loops/Conditionals Lacks built-in loops and conditionals Supports loops, conditionals, and control structures for more intricate logic
Examples sed ‘s/old/new/g’ file.txt replaces ‘old’ with ‘new’ globally in ‘file.txt’. awk ‘{ print $2 }’ file.txt prints the second field from each line in ‘file.txt’.

52. What is a Hard Link?

A hard link in shell scripting is a pointer directly to a file’s inode, there by giving the same file a different name. Hard links, as opposed to symbolic links, which point to filenames, point directly to the data within the file on the disk since they share the same inode. As long as there are still active hard links, deleting a file won’t get rid of its data or inode. Each file’s link count, which indicates the number of hard links connected to it, is displayed by the (ls -l )command. Hard links must be created within the same file system, and any changes made to the file through one hard link are immediately mirrored in all other hard links.

53. What is Soft Link?

A soft link, sometimes referred to as a symbolic link in shell scripting, is a unique form of a file that holds a path to another file or directory. Unlike hard links, symbolic links just provide a reference to the file’s location rather than actually pointing to the inode or file data. The symbolic link breaks if the original file is moved or deleted. Create shortcuts or aliases for files and folders using symbolic links to make it simpler to access them from other locations. They are able to link to files and directories in many file systems.
Using the (ln -s )command, one can create a symbolic link by supplying the target file or directory and the desired symbolic link name.

54. When should shell programming/scripting not be used?

Shell programming or scripting should not be used for complex software development tasks or applications that require high performance, extensive graphical interfaces, or intricate data manipulation. It is not suitable for projects demanding real-time processing, complex mathematical calculations, or sophisticated user interactions. Additionally, shell scripts may not be the best choice for large-scale applications with intricate architecture. In such cases, programming languages like Python, Java, C++, or specialized tools and frameworks are more appropriate for achieving better performance, maintainability, and scalability.

55. What does the .(dot) indicate at the beginning of a file name and how should it be listed?

A hidden file is one whose name starts with a . (dot). Every time we attempt to list the files, all files—hidden files excluded—are listed.
It will, however, be listed in the directory. Additionally, we must use the ls -a option, like $ ls -a, in order to list the hidden file.

56. What are the different blocks of a file system? Explain in brief.

The file system is divided into several core blocks or components, each of which serves a specific purpose in managing and storing the data efficiently. The files system’s main blocks are shown here:

Boot Block: The first file system block with the bootstrap code or boot loader that must be installed in order to start your computer.

Superblock: A crucial data structure that offers crucial metadata about the file system, such as its type, size, status, list of free and used blocks, and more, including information on each block’s status. For mounting and using the file system, it is essential.

Block INODE: Each file or directory is represented by an inode (index node), which also contains metadata about the corresponding file, including permissions, timestamps, file size, and pointers to the data blocks. Inode blocks are collections of inodes. Blocks of data are the actual blocks that hold file data, including directory entries pointing to other files or subdirectories as well as file contents.

FAT: File Allocation Table: a list that links the names of files to the corresponding inodes or data blocks. File systems like FAT and exFAT frequently use it.

FDT: File Descriptor Table: a table with entries from the inode table that serve as file descriptors. It assists in managing open files and the data that goes with them.

No-cost block list: a list that manages the file system’s free or available blocks, allowing for the effective allocation of blocks for new files and directories.

57. What is the alternative command available to echo and what does it do?

tput is an alternative command to echo.

58. How many types of control instructions are available in a shell? Explain in brief.

In a shell, there are three types of control instructions:

  1. Sequential Control: These instructions are executed one after the other in a sequential manner. They ensure that each command runs only after the previous one completes.
  2. Conditional Control: Conditional instructions, like ‘if’ statements, enable decision-making in scripts. They execute commands based on specified conditions, allowing for branching and different outcomes.
  3. Loop Control: Loop instructions, such as ‘for’ and ‘while’ loops, repeatedly execute commands until a specified condition is met, providing automation and repetitive task handling.

59. What is IFS?

IFS stands for Internal Field Separator. And it is one of the system variables. By default, its value is space, tab, and a new line. It signifies that in a line where one field or word ends and another begins.

60. What are the two files of the crontab command?

The crontab command in Unix-like operating systems utilizes two files: the system-wide crontab file located at /etc/crontab and user-specific crontab files stored in /var/spool/cron/crontabs directory. The system-wide file is typically used by administrators for tasks that affect the entire system, while users employ their individual crontab files to schedule and manage recurring tasks specific to their accounts.

61. What is Shebang in a shell script?

Shebang is a hash sigh ‘#’ followed by an exclamation mark ‘!’ Generally, this can be seen at the beginning or top of the script/program. Usually, a developer uses this to avoid repetitive work. Shebang mainly determines the location of the engine which is to be used in order to execute the script.

Example: #!/bin/bash
The above line also tells which shell to use.

62. In shell scripting, where you will find the login names of all the users on a system, and how they can be printed at the same time?

In shell scripting, you can find the login names of all users on a system by examining the “/etc/passwd” file, which contains user account information. To print all user login names simultaneously, you can use the “cut” command in combination with other commands like “awk” or “cut” to extract the necessary information. For instance, running “cut -d: -f1 /etc/passwd” will display a list of all user login names in the system.

63. What do you know about the MBR in the shell scripting? How it is useful for the users?

In shell scripting, MBR stands for Master Boot Record. It is a small but crucial data structure located in the first sector of a storage device, such as a hard drive. MBR contains information about the disk’s partitioning and the bootloader. It’s useful for users because it enables the system to boot, manage partitions, and load the operating system. Understanding and managing the MBR is essential for tasks like disk maintenance, repair, and dual-boot setups.

64. What is the difference between process and thread?

To put it in simple words, a thread is a small piece of code/instruction that needs to be executed in a process, whereas a process is a collection of one or more thread executions to complete one complete task.

A process consists of multiple threads that can share resources among them as they belong to the same process. And threads that belong to different processes cannot share their resources.

65. Without restarting the machine, how can we remove all the running processes?

All the running processes in the current shell can be removed using the Linux killall command.

66. Command to wipe out variables defined.

If we consider $ mm = 2018 as a variable defined by the user, then in order to wipe out the variable, the unset command is used.

Syntax: $ unset mm

67. What is thread in shell script and how can we use it?

Concurrent execution units within a shell script are referred to as threads in the context of shell scripting. However, unlike some other programming languages, traditional Unix-like shells (such as Bash) do not natively support multithreading within a script. 

Typically, in a shell script: Each line of a script or command is carried out in turn. Background execution or subshells can spawn subprocesses, but these are not true threads and run independently. You can employ the following methods for parallel or concurrent execution.

Background Performing: Using the & operator, you can run commands or scripts in the background so that they run concurrently with the main script. 

Subshells: Subshells, distinct instances of the shell, are where commands can be executed. These, however, don’t function as threads and operate separately. You might think about using other languages like Python, which have strong threading support, for true multithreading and parallelism in a shell-like environment. For instance, you can create and manage threads for concurrent execution within a script using Python’s threading module.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.