Shell Scripting Interview Questions

Last updated on Nov 08, 2023

Shell is an interface between the user and the kernel. Even it has only one kernel; a system can have many shells which can run simultaneously. whenever a user enters a command the shell communicates with the kernel to execute it and then displays the output to the user. Shell Scripting is a collection of commands put together into a file. The script is a command or an instruction given to process and these set of instructions put together in a file to perform some task.

In this article, you can go through the set of Shell Script interview questions most frequently asked in the interview panel. This will help you crack the interview as the topmost industry experts curate these at HKR training.

Let us have a quick review of the Shell Script interview questions

Most Frequently Asked Shell Scripting Interview Questions

1. What are the different types of variables used in Shell Script?

Ans: There are two variables used in the Shell Script.

  • System-defined variables are created or defined 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”.

2. What are the different types of commonly used shells on a typical Linux system?

Ans: There are primarily two kinds of shells in Linux OS, namely, Bourne Shell and C-Shell. Examples of derivative from each are as follows;

  1. Bourne Shell: Bourne Shell, Bourne-Again Shell, Korn Shell, POSIX Shell.
  2. C-Shell: C-Shell, TENEX C-Shell, Z-Shell.

3. How to check if the previous command was run successfully?

Ans:  Type the below code in q15.sh and run it.

#!/bin/sh

var=$?

if var=0

then

echo "Script was Run successfully"

else

echo "Script was unsuccessful"

fi

Output:

$ ./q15.sh

Script was Run successfully

4. What makes C shell a more preferable option than the Bourne Shell?

Ans: C is a more preferable option in the following cases:

  • All the commands can be aliased simply with the C shell but it is not possible in case of Bourne Shell.
  • Lengthy commands can be used again and again in C shells. Bourne shell doesn’t allow this in all the cases.
  • The command history can be accessed through the C shell but it cannot be accessed through the Bourne.

5. How Do You Remove A File?

Ans: To remove (delete) a file in a Unix-like system, you can use the rm command. 

For example: rm filename

Replace "filename" with the file name you want to delete. Be cautious when using the rm command, as it permanently deletes files, and there is no easy way to recover them. You can use the -i option for interactive mode, which prompts you to confirm each deletion, or the -r option to remove directories and their contents recursively. Always double-check the files you're deleting to avoid unintentional data loss.

6. What Are Pids?

Ans: A Process ID, or PID, is a unique numeric identifier assigned to each running process in an operating system. PIDs are crucial for managing and interacting with processes. They are used to start, stop, monitor, and signal processes. PIDs are essential for system administrators and programmers, allowing them to manage and troubleshoot processes efficiently. Common operations involving PIDs include killing misbehaving processes, checking process status, and tracking the execution of programs. PIDs are used extensively in Unix-like systems, and they help ensure the stability and control of the operating system by distinguishing between various running processes.

7. Write a script to print the first 10 elements of Fibonacci series.

Ans:

#!/bin/sh

a=1

b=1

echo $a


echo $b

for I in 1 2 3 4 5 6 7 8

do

c=a

b=$a

b=$(($a+$c))

echo $b

done

8. What are Vi Editor modes available?

Ans: There are different operations that can be performed in different modes. while working with Vi Editor.

  1. Command Mode: Launching Vi automatically starts command mode.
  2. Edit Mode: This mode provides an environment to edit text.
  3. Ex Mode: Vi editor interaction is made available with file processing instructions.

9. What Is Shell Scripting?

Ans: Shell scripting is writing a series of commands for a Unix or Unix-like operating system, executed in sequence as a script. A shell script is a text file containing a set of instructions that can be interpreted by a shell (command-line interpreter) to perform various tasks or automate processes. Shell scripts are often used for system administration tasks, task automation, and other tasks where you must execute commands.

10. Why is writing Shell Scripts important according to you?

Ans: Shell Scripting is important because of the following reasons. 

  1. Shell scripting is very useful and powerful while creating customized commands on your own.
  2. There are many tasks which make the process of automation easy.
  3. The users are responsible for providing the input and this clearly means the output if free from errors.
  4. It is time-saving.
  5. Many system administration tasks can be accomplished and can be automated.

11. State The Advantages Of Shell Scripting?

Ans: There are many advantages of shell scripting some of them are, one can develop their own operating system with relevant features best suited to their organization than to rely on costly operating systems. Software applications can be designed according to their platform.

12. What Are The Disadvantages Of Shell Scripting?

Ans:         

  • There are many disadvantages of shell scripting they are
  • Design flaws can destroy the entire process and could prove a costly error.
  • Typing errors during the creation can delete the entire data as well as partition data.
  • Initially process is slow but can be improved.
  • Portbility between different operating system is a prime concern as it is very difficult to   port scripts etc.

13. How to set an array in Linux?

Ans: 
Syntax in ksh:

Set –A arrayname= (element1 element2 ….. element)

In bash

A=(element1 element2 element3 …. elementn)

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

Ans: The blocks in the file system are as follows.

  • Super Block: This block mainly tells about the state of the file system such as how big it is, the maximum number of files that can be accommodated, etc.
  • Boot Block: This block represents the beginning of a file system. It contains the bootstrap loader program, which gets executed while booting the host machine.
  • Inode Table: All the entities in a UNIX are treated as files. So, the information related to these files is stored in an Inode table.
  • Data Block: This block contains the actual file contents.

15. What are the three different security provisions provided by UNIX for a file or data?

Ans: The three different security provisions are as follows.

  1. It provides a unique user id and password to the users for providing authentication, so that unknown or unauthorized cannot access it.
  2. It provides security at the file level by providing read, write and execute permissions to access the files.
  3. It provides security using file encryption. This method allows encoding a file in an unreadable format. Even if someone opens a file they cannot read its contents until and unless it is decrypted.

16. Write down the Syntax for all the loops in Shell Scripting.

Ans: 

For Loop:

for var in word1 word2 ... wordN

do

   Statement(s) to be executed for every word.

done

While Loop:

while command

do

   Statement(s) to be executed if the command is true

done

Until Loop:

until command

do

   Statement(s) to be executed until the command is true

done

17. How to find all the available shells in your system?

Ans: You can find all shells available in the system with $ cat /etc/shells.

Example:

$ cat /etc/shells

Execution over Shell Interpreter/Editor:

$ cat /etc/shells

Output:

/bin/sh

/bin/bash

/sbin/nologin

/bin/ksh

/bin/dash

/bin/tcsh

/bin/csh

18. How to debug the problems encountered in the shell script/program?

Ans: Below are common methods applied to debug the problems in the script.

  • Debug statements can be inserted in the shell script to output/display the information which helps to identify the problem.
  • Using set -x enables the debugging in the script.

19. Explain in brief about sed command with an example.

Ans: sed is an acronym for stream editor. It is used for editing a file without using an editor. It is used to edit a given stream i.e. a file or input from a pipeline.

Syntax: sed options file

Example:

Execution over Shell Interpreter/Editor

/u/user1/Shell_Scripts_2020> echo "Hello Word" | sed 's/Hello/Hi/'

Here ‘s’ command present in sed will replace string Hello with Hi.

Output:

Hi World

20. What is Shebang in a shell script?

Ans: Shebang is a # sign followed by an exclamation i.e. !. In general, it is seen at the beginning or top of the script/program. Developers will use this to avoid repetitive work. Shebang determines the location of the engine which is to be used in order to execute the script.

Here ‘#’ symbol is called hash and ‘!’ is called a bang.

Example: #!/bin/bash

The above line also tells which shell to use.

Shell Scripting Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

21. What is the function of utilities that come with the open client driver in the shell scripting?

Ans: The utilities simply connect the system with a database server. The users have to perform many tasks which are relevant and important in scripting. The scripting requires more data and information and it is not always possible to keep the same at that particular location only. The users have to make sure of an error-free outcome in this approach.

22. How will you copy a file from one machine to another?

Ans: The utilities such as "ftp," "scp" or "rsync" to copy a file from one machine to another.

Example:

Using ftp:

FTP hostname

>put file1

>bye

The above command copies file file1 from the local system to the destination system whose hostname is specified.

23. In Shell scripting, how can the user frequently monitor a log file that is updating?

Ans: In the shell scripting, there is a concept of tailing which can be applied to monitor a log file frequently. It is done by using the tail-f filename. It enables the users to display the previous ten lines on the output. The same reflects the part of the file which is updating continuously. 

24. What are the different commands available to check the disk usage?

Ans: There are three different commands available to check the disk usage.

  1. df: It is used for checking the free disk space.
  2. du: It is used for checking the directory wise disk usage.
  3. dfspace: It is used for checking the free disk space in terms of MB.

25. Write a shell script to get current date, time, username and current working directory.

Ans: Type the following code in the “q52.sh” file

#!/bin/sh

echo "Hello, $LOGNAME"

echo "Today's date is `date`"

echo "Username is `who i am`"

echo "Current directory is `pwd`"

Output:

[hkr@localhost ~]$ ./q52.sh

Hello, hkr

Today's date is Wed Sep 9 02:23:58 EDT 2020

Username is hkr  pts/0       2020-09-09 02:20 (:0)

Current directory is /home/hkr

26. How to get part of a string variable by using echo command?

Ans: Type and run the following code in the q34.sh file.

#!/bin/sh

echo ${variable:x:y}

#x - start position

#y - length

variable="My name is Krishna, and I work at Hkr."

echo ${variable:11:7} # will display Krishna

Output:

[hkr@localhost ~]$ ./q34.sh

Krishna

27. How to print PID of the current shell?

Ans: Type and run the following code to print PID in q37.sh file.

#!/bin/sh

for PID in $$

do

echo $PID

done

Output:


[hkr@localhost ~]$ ./q37.sh

7365

28. How to print all array elements with their respective indexes and print the first array?

Ans: Type and run the following code to print PID in q38.sh file.

!/bin/sh

array=("This" "is" "Shell" "Scripting")

echo ${array[@]} # prints the array elements

echo ${!array[@]} # prints the index of array elements

echo ${array[0]} # prints first array element

Output:

[hkr@localhost ~]$ ./q38.sh

This is Shell Scripting

0 1 2 3

This

29. What command needs to be used to take the backup?

Ans: The command to take a backup depends on what you want to back up. In Unix-like systems, you can use various commands for various backups. Common commands include:

  • cp: For creating a basic copy of files or directories.
  • rsync: For synchronizing and copying files and directories efficiently.
  • tar: For creating compressed and archived backups.
  • dd: For low-level copying of data, often used for disk or partition backups.
  • Database-specific commands (e.g., mysqldump for MySQL databases) for database backups.

The specific commands and options you use will depend on your backup requirements and the type of data you're dealing with.

30. What are positional parameters? Explain with an example.

Ans: Positional parameters are the variables defined by a shell. These parameters are used whenever there is a need to convey information to the program. It can be done by specifying arguments at the command line.

There is a total of 9 positional parameters present i.e. from $1 to $9.

Example: $ Test Shell is a Command Line Interpreter.

In the above statement, positional parameters are assigned like this.

$0 -> Test (Name of a shell program/script)

$1 -> Shell

$2 -> is and so on

31. What are the different types of Shells available?

Ans: There are mainly four important types of shells that are widely used.

  1. Bourne Shell (sh).
  2. C Shell (csh).
  3. Korn Shell (ksh).
  4. Bourne Again Shell (bash).

32. What does it mean by #!/bin/sh or #!/bin/bash at the beginning of every script?

Ans: A script may specify “#!/bin/bash” on the first line to denote that the script should always run with bash, rather than another shell. The “/bin/sh” is an executable representing the system shell. It is implemented as a symbolic link pointing to the executable for whichever shell is the system shell.

33. What are the two files of crontab command?

Ans: The two files of crontab command are.

  1. cron.allow: It decides which users should be permitted from using crontab command.
  2. cron.deny: It decides which users should be prevented from using the crontab command.

34. I want to connect to a remote server and execute some commands, how can I achieve this?

Ans: You can use ssh to do this:

Syntax:

ssh username@serverIP -p sshport

Example:

ssh root@122.52.251.171 -p 22

After the above command is executed, you will be asked to enter the password.

35. I have two files and I want to print the records which are common to both.

Ans: You can use the command "comm" as follows:

comm -12 file1 file2 ... 12 

This will suppress the content which is unique to the first and second file respectively.

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

Ans: To remove all the running processes without restarting the machine, the Linux killall command can be used in shell scripting. This command allows you to terminate multiple processes at once by specifying their names or other identification criteria. By executing the killall command in the current shell, all the running processes will be effectively removed without the need to restart the machine.

37. What is the difference between process and thread?

Ans: 

The main distinction between a process and a thread lies in their individual functionalities and relationship within a computing system.

A process can be understood as a self-contained program that is being executed within the operating system. It consists of a data set, code instructions, and various system resources. In essence, a process represents a complete task or job that needs to be accomplished. This includes memory space, file descriptors, and other relevant system resources acquired by the operating system to execute the program. While running, a process operates independently from other processes, executing its own set of code instructions.

On the other hand, a thread can be seen as a smaller unit of execution within a process. It is essentially a sequence of instructions that can be scheduled and executed by the operating system. Threads share resources, such as memory and file descriptors, with other threads that belong to the same process. Unlike processes, threads are not self-contained entities, but rather exist within the context of a process. Multiple threads can be present within one process, allowing for concurrent execution of tasks.

The crucial distinction between processes and threads lies in their ability to share resources. Threads within a single process can directly access shared memory, variables, and other resources, making them ideal for tasks that require coordination or communication between different parts of a program. Different processes, however, cannot directly share resources. Each process operates in isolation and must communicate via inter-process communication (IPC) mechanisms, such as pipes or sockets, to exchange information or synchronize actions.

In summary, a process represents a complete program or task, while a thread is a smaller unit of execution that operates within a process. Processes operate independently from each other, while threads within a single process can share resources and execute code concurrently.

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

Ans: 

In shell scripting, the MBR (Master Boot Record) refers to a vital data structure situated in the initial sector of a storage device, typically a hard drive. Its primary function is to store crucial information related to disk partitioning and the bootloader. The MBR plays a key role in facilitating the booting process, managing partitions, and loading the operating system.

For users, understanding and effectively managing the MBR is essential in a variety of scenarios. One significant advantage is that it enables users to ensure the system boots successfully. By possessing knowledge about the MBR, users can identify and troubleshoot issues that may arise during the boot process.

Furthermore, the MBR proves beneficial in managing disk partitions. It stores essential records that define the layout of the storage device, enabling users to create, modify, or delete partitions as per their requirements. This functionality is particularly useful in scenarios where users need to allocate disk space for specific purposes, such as creating separate partitions for different operating systems, implementing dual-boot setups, or dedicating specific partitions for data storage.

Additionally, the MBR serves as a gateway for loading the operating system. It contains the necessary code to locate and initiate the system's bootloader, which is responsible for initiating the operating system. This functionality empowers users to control the operating system that is loaded when their system starts up, allowing them to, for instance, switch between different operating systems in a dual-boot configuration.

Overall, a thorough understanding of the MBR in shell scripting is pivotal for users involved in tasks like disk maintenance, repair, and implementing dual-boot setups. By harnessing the power of the MBR, users can effectively manage partitions, troubleshoot boot issues, and have greater control over the operating system loaded on their system.

39. What is IFS?

Ans: IFS, also known as the Internal Field Separator, is a system variable that plays a key role in dividing and separating fields or words within a line of text. Its default value consists of three different characters: space, tab, and a new line. Essentially, IFS serves as a marker that indicates the boundary between individual fields or words, allowing for efficient parsing and processing of data. It is an essential component in various computing systems and programming languages, enabling the extraction and manipulation of specific portions of text or data.

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

Ans: 

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

1. Sequential Control: These instructions are executed one after another in a sequential manner. They ensure that each command runs only after the previous one completes. This allows for a step-by-step execution of commands, ensuring the desired order of operations.

2. Conditional Control: Conditional instructions, such as 'if' statements, provide decision-making capabilities within shell scripts. They allow for the execution of specific commands based on specified conditions. This branching capability enables different outcomes depending on the conditions met, enhancing the flexibility and adaptability of shell scripts.

3. Loop Control: Loop instructions, like 'for' and 'while' loops, enable the repetition of commands until a specific condition is met. This automation feature allows for the execution of repetitive tasks without the need for manual intervention. Loops provide efficiency and enable handling of tasks that require repetitive operations.

In summary, the shell offers three primary types of control instructions: sequential control for executing commands in a specific order, conditional control for decision-making based on conditions, and loop control for automating repetitive tasks. These control instructions provide the necessary flexibility and automation capabilities in shell scripting.

Subscribe to our YouTube channel to get new updates..!

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

Ans: An alternative command to echo is called "tput". Tput is a command that performs similar functions to echo. It allows users to print text or values onto the terminal screen. However, tput has additional capabilities beyond echoing text, such as controlling terminal settings, displaying information about the terminal, and manipulating cursor positions. Therefore, tput not only serves as an alternative to echo but also provides more functionality for interacting with the terminal environment.

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

Ans: 

The dot (.) at the beginning of a file name indicates that the file is hidden. In file systems like Unix, Linux, and macOS, any file whose name starts with a dot is considered hidden. This means that these files are not normally shown when listing the files in a directory. By default, when we use commands like "ls" to list files in a directory, hidden files are excluded from the output.

However, if we want to see the hidden files in a directory, we can use the "ls -a" command. The "ls -a" option allows us to list all files, including the ones with names starting with a dot. By using the "ls -a" command, we can view and access hidden files in the directory.

To summarize, the dot (.) at the beginning of a file name signifies that the file is hidden. It won't be displayed when listing files, except when using the "ls -a" command.

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

Ans: Shell programming or scripting should not be used in scenarios that involve complex software development tasks or applications requiring high performance, extensive graphical interfaces, or intricate data manipulation. It is not suitable for projects that demand real-time processing, complex mathematical calculations, or sophisticated user interactions. Additionally, shell scripts may not be the best choice when working on large-scale applications with intricate architecture, as they lack the level of performance, maintainability, and scalability that programming languages like Python, Java, or C++ provide. Instead, specialized tools and frameworks should be considered to achieve better outcomes in terms of performance, maintainability, and scalability when dealing with these types of projects.

44. What is Soft Link?

Ans: 

A soft link, also known as a symbolic link in shell scripting, is a special type of file that holds a reference to another file or directory. Unlike hard links which directly point to the inode or file data, symbolic links simply provide a path to the location of the original file.

The purpose of a symbolic link is to create shortcuts or aliases for files and folders, making it easier to access them from different locations. By using symbolic links, you can establish connections to files and directories across various file systems.

To create a symbolic link, you would use the "ln -s" command, providing the target file or directory along with the desired name of the symbolic link. It's important to note that if the original file is moved or deleted, the symbolic link will break, as it only references the file's location rather than its actual contents.

45. What is a Hard Link?

Ans: 

A hard link is a specific type of link in shell scripting that acts as a direct pointer to a file's inode. It effectively gives the same file a different name without duplicating any of the file's data. Unlike symbolic links, which simply point to filenames, hard links point directly to the data stored within the file on the disk. This is possible because all hard links for a given file share the same inode.

One important characteristic of hard links is that they preserve the data and inode of a file even if it is deleted. This means that as long as there are still active hard links pointing to a file, its data and inode will not be removed from the system. The link count of a file, which indicates the number of hard links connected to it, can be viewed using the "ls -l" command.

It is worth noting that hard links can only be created within the same file system. This means that the file and all its hard links must reside in the same storage location. Additionally, any modifications made to the file through one hard link will immediately be reflected in all other hard links connected to the same file. This behavior ensures that all hard links always represent the same up-to-date version of the file's contents.

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

Ans: In a shell script, concurrent processes or parallel execution can be effectively handled using various tools and techniques. Some common approaches include:
1. Using tools like xargs or parallel: These tools allow for efficient parallel execution by distributing the workload across multiple processes. They can handle a large number of tasks simultaneously, improving overall execution time.
2. Employing background processes: By executing commands in the background using the "&" operator, you can initiate multiple processes simultaneously. This allows for concurrent execution, where each process runs independently while the script continues its execution.
3. Utilizing job control operators: Features like the "wait" command ensure that the script waits for the completion of concurrent processes before continuing execution. This is particularly useful when dependent tasks need to be coordinated before proceeding further.
Overall, incorporating these techniques into a shell script allows for efficient handling of concurrent processes and parallel execution, enhancing performance and productivity.

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

Ans: 

In order to read and parse CSV or delimited files in a shell script, you have several options available. One of these options is using the 'awk' command with the appropriate field separator (-F) to extract and manipulate specific columns from the file. For instance, using the following command will allow you to easily extract columns from a CSV file:

`awk -F ',' '{print $1, $3}' file.csv`

This will print the first and third columns of the CSV file, assuming that the columns are separated by commas.

Alternatively, you can also use the 'cut' command to extract specific columns from a file. For example:

`cut -d ',' -f 1,3 file.csv`

This command will extract the first and third columns from the CSV file using a comma (',') as the delimiter.

Additionally, you can use the 'read' command to read and parse delimited files line by line. By setting the IFS (Internal Field Separator) variable to the appropriate delimiter, you can iterate through the file and extract the necessary values. Here's an example:

```
while IFS=',' read -r col1 col2 col3
do
# Use col1, col2, col3 as needed
echo "Column 1: $col1, Column 2: $col2, Column 3: $col3"
done < file.csv
```

This script will read each line of the CSV file and separate the values based on the comma delimiter. You can then access each column using the variables col1, col2, and col3 within the loop, and perform any desired processing.

These methods provide different approaches to read and parse CSV or delimited files in a shell script, offering flexibility depending on your specific needs.

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

Ans: 

In Bash, an alternative to using if-else if-else statements is to utilize a case statement. The syntax for a case statement is different from that of a switch case. Instead of "switch" and "case," the syntax for a case statement involves using "case" and "esac." Additionally, there is no need to include a break statement.

The general structure of a case statement in Bash is as follows:

```
case expression in
pattern1) commands;;
pattern2) commands;;
...
esac
```

Within this structure, you can specify different patterns that are evaluated against an expression. When a pattern matches the expression, the corresponding commands associated with that pattern are executed. It is important to note that each command line should end with a double semicolon ";;" to indicate the end of the commands for a particular pattern.

By utilizing the case statement, you can effectively replace a series of if-else if-else statements and simplify the logic flow of your script.

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

Ans: 

To calculate the execution time of a command or script in a shell script, you can utilize the time command. This command allows you to measure the duration it takes for a specific command or script to execute.

To implement it, you simply need to prefix the command or script you want to measure with the time command. For instance, if you have a shell script named "myscript.sh" that you want to measure, you would write the following:

```
time ./myscript.sh
```

By running this line in your shell script, the time command will provide you with information about the execution time of the script. It will display output that includes the real time, user time, and system time.

The real time represents the total time it takes for the command or script to execute, including any time spent waiting for resources. The user time indicates the amount of CPU time used by the command or script's own executions. The system time specifies the CPU time used by system calls made by the command or script.

By appending the time command before a specific command or script, you can effectively calculate the execution time within your shell script. This information can be valuable for analyzing and optimizing the performance of your scripts or commands.

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

Ans: 

In a shell script, arrays can be declared and accessed using square brackets and indexes. To create an array, simply assign a list of elements to a variable, enclosing the elements in parentheses and separating them with spaces. For example:

```shell
myarray=("apple" "banana" "cherry")
```

To access a specific element in the array, you can use the array name followed by an index enclosed in square brackets. The index starts at 0 for the first element. For example, the following code will output "apple":

```shell
echo "${myarray[0]}"
```

You can also iterate over all the elements in an array using a loop or a special syntax. For example, to loop through all the elements in the `myarray` array:

```shell
for item in "${myarray[@]}"; do
echo "$item"
done
```

In the above example, `"${myarray[@]}"` expands to all elements in the array, allowing you to iterate over them one by one.

You can modify elements in an array by directly assigning a new value to a specific index. For example, to change the second element to "orange", you can do:

```shell
myarray[1]="orange"
```

Arrays in shell scripts are versatile and useful for storing and manipulating collections of data. They provide a convenient way to manage multiple related values within a single variable.

51. Explain Crontab?

Ans: 

Crontab is a utility designed for Unix-based systems that serves as a time-based scheduler for automating repetitive tasks. It allows users to schedule and execute specific commands at predefined time intervals, such as minutes, hours, days, months, or even days of the week. By utilizing crontab, users can automate various tasks like backups, software updates, and running scripts automatically at specific times.

Each user on a Unix-like system has the ability to have their own crontab, which acts as an individualized schedule for executing commands. Users have the flexibility to define their desired time schedule by specifying the exact minute, hour, day, month, or day of the week when a particular command should run.

To make changes to their crontab, users can use the command "crontab -e" to open and edit their schedule file in the default text editor. This allows users to easily modify their existing commands or add new ones without directly editing system files or configurations. Consequently, crontab simplifies the process of system maintenance and task automation on Unix-like systems by providing a user-friendly interface to manage scheduled tasks.

52. What is the significance of $#?

Ans: The significance of the $# in shell scripting is that it serves as a built-in variable that represents the number of arguments passed to a script or function. Its purpose is to provide scriptwriters with the ability to determine the count of positional parameters or arguments that are provided when executing the script. This information can be crucial for creating conditional logic based on the number of arguments or for efficiently iterating through and processing them within the script. By utilizing the $# variable, scriptwriters can develop more dynamic and flexible scripts that can adapt to varying numbers of inputs, enabling them to handle different scenarios and requirements more effectively.

53. How do you define whether a given link is hard or soft?

Ans: 

To determine whether a given link is hard or soft in shell scripting, we primarily consider whether the link is symbolic or represents a physical file or directory. This differentiation plays a vital role in effective file management and scripting logic.

In practical terms, we can define a link as a hard link if it directly points to an actual file or directory in the file system. A hard link creates a new reference to the same underlying file, essentially setting up multiple paths to access the same data. Changes to the file or directory through one hard link will be reflected in all other hard links associated with it.

On the other hand, a soft link, also known as a symbolic link, is a special type of link that acts as a pointer to another file or directory. In contrast to a hard link, a soft link points to the target file or directory indirectly, using its absolute or relative path. Therefore, a soft link does not create an additional reference to the underlying data but rather acts as a shortcut or alias.

To programmatically determine whether a link is hard or soft, we can utilize the 'test' command in shell scripting. By using the '-h' flag with the 'test' command, we can evaluate if a given link is a symbolic link or represents an actual file or directory. If the command returns true, it signifies that the link is a symbolic link, indicating a soft link. Conversely, if the command returns false, it indicates that the link represents an actual file or directory, classifying it as a hard link.

This categorization of links, either as hard or soft, facilitates efficient file management and helps in scripting logic. It enables us to perform specific operations based on the type of link encountered, making it easier to handle different scenarios and maintain proper file structure within a script.

54. What are CLI and GUI?

Ans: 

CLI (Command Line Interface) refers to a text-based interface that allows users to interact with a computer system by typing specific commands. It can be found widely used in Unix-like systems. CLI offers efficiency and speed for experienced users, as well as the ability to automate tasks through scripting. However, it requires users to have knowledge of the specific commands and syntax.

On the other hand, GUI (Graphical User Interface) is a visual interface that presents icons, windows, and other graphical elements to users, enabling them to interact with the computer system. GUI is designed to be user-friendly and suitable for beginners, as it eliminates the need for memorizing complex commands. GUIs are commonly found in popular operating systems such as Windows and macOS, as well as in various desktop applications.

While CLI relies on text and command inputs, GUI simplifies interaction by providing a visual representation of system functions. This makes GUI more intuitive and accessible, especially for individuals who are not familiar with the underlying commands or technical aspects of the system. GUIs allow users to perform tasks by using their mouse or touch input and selecting options through menus and buttons.

In summary, CLI and GUI are two different interfaces that enable users to interact with computer systems. CLI is efficient for experienced users and scripting, commonly used in Unix-like systems, while GUI provides a user-friendly, visual interface suitable for beginners and is commonly found in Windows, macOS, and desktop applications.

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

Ans: 

In shell scripting, arithmetic calculations can be performed using various methods. Two commonly used approaches are the "expr" command and arithmetic expansion using double parentheses (( )).

The "expr" command allows you to evaluate expressions and perform arithmetic calculations. For example, to add two numbers together, you can use the following syntax:
```
result=$(expr 2 + 2)
```
In this example, the result variable will store the value of 4, which is the sum of 2 and 2. To print the result, you can use the "echo" command, like this:
```
echo $result
```
This will output 4 in the terminal.

Another method is arithmetic expansion, which uses double parentheses (( )). This approach allows you to perform arithmetic calculations using a more concise syntax. For instance, to add two numbers, you can use the following syntax:
```
result=$((2 + 2))
```
Similar to the previous example, the result variable will store the value of 4. To display the result, you can again use the "echo" command:
```
echo $result
```
This will also output 4 in the terminal.

These are just two ways to perform arithmetic calculations in shell scripting. Depending on your specific needs, you may also consider other options such as using the "let" command or arithmetic expansion with single parentheses. Regardless of the method you choose, arithmetic calculations in shell scripting are straightforward and allow you to perform various mathematical operations.

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

Ans: 

To count the number of occurrences of a specific word in a file using shell scripting, you can employ the powerful grep command with the -c option. Here's how you can do it:

1. Open your terminal or command prompt.
2. Navigate to the directory containing the file you want to search.
3. Use the grep command followed by the -c option, the word you want to count, and the file name:

```
grep -c "specific-word" file.txt
```

Replace "specific-word" with the actual word you want to count, and "file.txt" with the name of your file.
4. Press Enter to execute the command.
5. The terminal will display the total count of occurrences of the specified word in the file.

The -c option in grep stands for "count" and is specifically designed to output the total number of matching lines found in a file. By enclosing the word in double quotes, you ensure that grep treats it as a whole word and not as part of another word.

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

Ans: 

Creating and using environment variables in a shell script involves a few steps.

To create an environment variable, you need to assign a value to a variable. For example, you can create a variable called "MY_VARIABLE" and assign it the value "Hello, World!".

Once you have assigned a value to the variable, you can make it an environment variable using the "export" command. By using "export MY_VARIABLE", you are telling the shell to make the variable visible to all child processes spawned from the current shell.

To use the environment variable in your shell script, you can simply reference it by its name. For instance, if you want to print the value of "MY_VARIABLE", you can use the command "echo $MY_VARIABLE". The dollar sign followed by the variable name indicates that you want to use the value stored in that variable.

Environment variables are particularly useful when you want to share data between different processes running in the shell or when you want to configure certain settings that are needed across various scripts or programs.

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

Ans: The difference between $@ and $* lies in how they handle positional arguments. When using $*, all the arguments are considered as a single string. On the other hand, when using $@, each quoted argument is treated as an individual argument. So, while $* treats the entire group of arguments as a complete string, $@ recognizes and handles each argument separately.

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

Ans: 

To schedule a shell script to run at a specific time using Cron, you can follow these steps:

1. Open your terminal or command prompt.
2. Type the command "crontab -e" and press Enter. This will open the crontab file for editing.
3. In the crontab file, you can specify the desired time and frequency for the script to run using the Cron syntax.
- The syntax for specifying the time consists of five fields: minute, hour, day of month, month, and day of week.
- You can use specific values, range of values, wildcards, or predefined keywords to specify the time.
- For example, to schedule the script to run every day at 9 AM, you can use "0 9 * * *".
4. After specifying the time, you need to specify the command or script that you want to run.
- Make sure to provide the full path to the script if it's not in the default search path.
- For example, if your script is located at /path/to/script.sh, you would add "/path/to/script.sh" after specifying the time.
5. Save the changes and exit the crontab file.

Once you've scheduled the script using Cron, it will run automatically at the specified time and frequency. Cron is a versatile tool that allows you to schedule various tasks, including running shell scripts, on Unix-based systems.

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

Ans: 

To compare two strings in a shell script, you can use the conditional syntax of the bash shell. Here's an example of how you can do it:

```bash
if [ "$str1" = "$str2" ]; then
# The strings are equal
echo "The strings are equal"
else
# The strings are not equal
echo "The strings are not equal"
fi
```

In the example above, the `"$str1"` and `"$str2"` variables represent the strings that you want to compare. The `=` operator checks if the strings are equal. If the strings are equal, the script will execute the statements within the `if` block, which in this case is an echo statement informing that the strings are equal. Otherwise, if they are not equal, the statements within the `else` block will be executed, and it will echo that the strings are not equal.

You can modify the code accordingly to perform any other actions based on the outcome of the string comparison.

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

Ans: 

To redirect the output of a command to a file and display it on the terminal simultaneously, you can use the `tee` command. The `tee` command is a useful tool that allows you to send the output of a command to both a file and the standard output (terminal) at the same time.

Here is an example of how to use `tee` to achieve this:

1. Start by entering the command you want to run, followed by the pipe symbol (`|`).
2. After the pipe symbol, write the `tee` command, followed by the name of the file you want to redirect the output to. For example, `tee output.txt`.
3. Finally, press Enter to execute the command.

Once the command is executed, the output will be both displayed on the terminal and saved in the specified file (`output.txt` in this case).

Here's an example command to illustrate how this works:

```
command | tee output.txt
```

By using this command, the output generated by the `command` will be shown on the terminal, and simultaneously, it will be saved to the `output.txt` file.

Shell Scripting Training Certification

Weekday / Weekend Batches

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

Ans: 

Handling errors and exceptions in a shell script is essential to ensure smooth execution and prevent unexpected issues. There are several techniques and commands available to effectively handle errors and exceptions.

1. Exit on Error:
One approach is to use the `set -e` option at the beginning of the script. This setting ensures that the script will immediately exit if any command returns a non-zero status, indicating an error. By enabling this option, you can prevent further execution of the script when an error occurs, thus avoiding potential issues that might arise from continuing with a faulty execution.

Example:
```shell
#!/bin/bash
set -e
# Shell script commands here
```

2. Error Message Display:
To provide clear and meaningful error messages to users, you can utilize the `echo` command or other standard output functions. By displaying informative error messages, you enable users who encounter errors to better understand the issue and take appropriate actions.

Example:
```shell
#!/bin/bash
if [ ! -f "$file" ]; then
echo "Error: File '$file' does not exist." >&2
exit 1
fi
```

3. Signal Handling:
The `trap` command is useful for catching and handling specific signals or errors within a shell script. It allows you to define custom actions when certain conditions occur, such as handling a specific signal or catching exceptions. By utilizing this command, you have greater control over error handling by specifying how the script should react to various events.

Example:
```shell
#!/bin/bash
# Trap specific signal or error
trap 'echo "Error: Terminating the script."; exit 1' ERR
# Shell script commands here
```

4. Logging Errors:
Logging errors can be beneficial for both troubleshooting and tracking purposes. By redirecting error messages to a log file using the `>>` operator, you can maintain a record of encountered errors and gain insights into potential patterns or issues that need addressing.

Example:
```shell
#!/bin/bash
# Redirect error output to a log file
exec 2>> script_errors.log
# Shell script commands here
```

By employing these techniques and commands, you can handle errors and exceptions effectively in a shell script, ensuring the script's smooth execution and facilitating easier troubleshooting if errors occur.

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

Ans: 

In a shell script, you can read input from a file line by line using a while loop in combination with the read command. Here's how you can do it:

1. Open the file for reading:
```shell
while IFS= read -r line; do
# Process each line here
done < input.txt
```

2. The `while` loop will continue iterating as long as the `read` command is successful in assigning a line from the file to the `line` variable.

3. Inside the loop, you can process each line by adding your desired commands. For example, you can extract values, perform calculations, or manipulate the data.

4. To access the actual content of each line, you can use the `line` variable within the loop. For instance, you might use `echo "$line"` to display the line on the console, or apply string operations on this variable.

5. The option `-r` is used with `read` to prevent it from treating backslashes (\) as escape characters.

6. Setting `IFS` to an empty value (`IFS=`) ensures that leading and trailing whitespaces are preserved during the reading process.

7. Finally, the input redirection (`<`) is used to specify the file `input.txt` from which the lines will be read.

By using a while loop with the read command in this manner, you will be able to read input line by line from a file within a shell script and process it as desired.

64. What is LILO?

Ans: 

LILO, short for Linux Loader, is a boot loader that has been widely used in Linux systems. Its primary function is to initialize and manage the boot process by loading the Linux kernel into memory when the system starts up. This crucial operation allows the Linux operating system to take control of the computer hardware and subsequently launch the necessary processes to start the system.

LILO played a significant role in the early days of Linux distributions, as it effectively loaded the Linux kernel and allowed users to choose which operating system or kernel version they wanted to boot into. It was particularly useful in situations where multiple operating systems or different versions of Linux were installed on the same machine.

However, over time, LILO has given way to GRUB (GRand Unified Bootloader). This transition occurred primarily because GRUB offers more extensive features and increased flexibility in managing multiple operating systems and file systems. With GRUB, users can have finer control over the booting process and can easily switch between various operating systems or even different configurations of the same operating system.

In summary, LILO is a legacy boot loader that has been traditionally utilized in Linux systems to load the Linux kernel into memory during system startup. While it served an essential purpose in the past, it has been largely replaced by the more advanced GRUB bootloader, which provides enhanced functionality and improved flexibility in handling multiple operating systems and file systems.

65. What are control instructions in shell scripting?

Ans: 

Control instructions in shell scripting are essential commands that are used to define and control the flow and logic of a script. They enable precise program control by facilitating decision-making and handling repetitive tasks. These instructions include conditional statements, which allow the script to execute different code blocks based on specified conditions. This is achieved through the use of if-else statements, where certain actions are performed if a condition evaluates to true, and different actions are performed if the condition evaluates to false.

Another type of control instruction is loops, which allow a specific set of instructions to be repeated multiple times until a certain condition is met. Loops help automate repetitive tasks in a script, leading to improved script functionality and efficiency. For instance, the for loop allows for a block of code to be executed a predetermined number of times, iterating over a set of items or a range. On the other hand, the while loop repeats a block of code until a specified condition becomes false.

Additionally, shell scripting provides the case statement, which allows for multiple conditional branches based on the value of a certain variable or expression. This statement simplifies decision-making by providing a concise way to handle different scenarios.

By mastering control instructions in shell scripting, users gain the ability to automate processes and efficiently manage data. They empower script authors to create dynamic scripts that adapt to varying conditions, resulting in more effective and productive shell scripting.

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

Ans: 

In a shell script, one of the commonly used commands to read input from the user is the 'read' command. This command allows the script to interact with the user by prompting them for information and capturing their response.

To use the 'read' command, you start by specifying a variable where you want to store the user's input. For example, you can define a variable called 'input' like this:

```shell
read -p "Please enter your name: " input
```

In the above example, the '-p' option is used to display a prompt to the user, asking them to enter their name. The user's input will then be assigned to the 'input' variable.

You can also use the 'read' command without the '-p' option if you don't need a specific prompt. For example:

```shell
read input
```

In this case, the script will simply wait for the user to enter their input on a new line.

Once the 'read' command is executed, the script will wait for the user to provide their input. The user can enter their input followed by pressing the Enter key. The 'read' command will then capture the input and store it in the specified variable.

After the 'read' command, you can proceed to use the value stored in the variable in your script as needed. For example, you can display the user's input or use it for further calculations.

Overall, the 'read' command provides a way for shell scripts to interact with users and capture their input to be used in various operations within the script.

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

Ans: 

Conditional statements in a shell script are designed to add decision-making capabilities to the script. They allow the script to perform specific actions based on certain conditions. In shell scripting, the primary construct for implementing conditional statements is the 'if' statement.

To use conditional statements in a shell script, you start by using the 'if' keyword, followed by a space, an opening bracket '[', the condition that you want to check, and a closing bracket ']'. After the closing bracket, you use the semicolon and then the 'then' keyword.

Following the 'then' keyword, you provide the commands or actions that should be executed if the condition inside the 'if' statement evaluates to true. These commands are enclosed between the 'then' keyword and the 'fi' keyword.

It is important to note that each command or action within the conditional block should be placed on a new line, and to ensure proper syntax, you need to use a semicolon after each command.

If you need to include alternative actions for when the condition evaluates to false, you can use the 'else' keyword after the 'then' block. The 'else' keyword is followed by the commands that will be executed if the condition is false. Again, it is important to enclose these commands between the 'else' keyword and the 'fi' keyword.

To summarize, conditional statements in shell scripting are executed by using the 'if' statement. The condition is placed inside square brackets [ ], followed by the 'then' keyword. The commands within the 'then' block are executed if the condition is true. Additionally, you can include alternative actions for when the condition is false by using the 'else' keyword.

68. What is a kernel?

Ans: A kernel is a pivotal software component at the core of an operating system. It serves as the overseer and conductor, managing and coordinating all the essential operations of a computer and its underlying hardware. Its role is to ensure smooth interaction between software programs and hardware components, facilitating tasks such as memory management, process scheduling, device control, and overall system stability. In essence, the kernel acts as the bridge that enables different software applications to effectively communicate and utilize the resources of a computer system.

69. How is a shell script written?

Ans: A shell script is written by creating a plain text file with the ".sh" extension. You can use any text editor like vi, nano, or cat to write the script. The text editor allows you to input the commands and instructions that you want the script to execute. Once you have finished writing the script, you can save it with the ".sh" extension to indicate that it is a shell script. This file will then be interpreted by the shell, allowing it to execute the commands and perform the desired tasks outlined in the script.

70. What is the significance of shell scripting skills in the technology industry?

Ans: 

Shell scripting skills play a crucial role in the technology industry, and their significance cannot be overstated. In recent times, there has been a remarkable surge in job postings specifically seeking professionals with expertise in shell scripting. This increasing demand indicates a promising and rewarding career path for those who possess these skills.

Shell scripting, at its core, involves writing a series of commands in a shell (command-line interpreter) to automate various tasks and processes in a computer system. It allows for the efficient execution of complex operations by automating repetitive tasks, managing file systems, and facilitating communication between different programs. Thus, the ability to write effective shell scripts not only streamlines and simplifies workflows but also enhances productivity in the technology industry.

Moreover, the importance of shell scripting extends beyond its practical applications. A strong foundation in shell scripting demonstrates proficiency in Linux-based operating systems, which are widely used in server environments and cloud computing. This knowledge is particularly valuable considering the increasing prevalence of open-source technologies and the growing importance of efficient system administration.

Furthermore, mastering shell scripting is also crucial for career advancement. Professionals who possess this skill set have a competitive edge in the job market. When facing job interviews, candidates who are well-versed in shell scripting are better equipped to tackle the specific challenges and questions posed in such interviews. Having a comprehensive understanding of shell scripting interview questions and being able to provide articulate and well-thought-out answers further improves one's prospects in this constantly growing field.

In conclusion, shell scripting skills hold immense significance in the technology industry. The increasing demand for professionals with this expertise, coupled with the practical benefits of automating tasks and managing systems, highlights the importance of acquiring and honing these skills. In such a competitive landscape, individuals who possess a strong foundation in shell scripting and are well-prepared for related interviews will find themselves well-positioned for success in this rapidly evolving industry.

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

Ans: 

What are the benefits of using pipe commands in shell scripting?
Using pipe commands in shell scripting offers several benefits. It streamlines tasks by allowing the output of one command to directly flow into the input of another command. This enhances efficiency by eliminating the need to store intermediate results in files. Pipe commands also enable complex data processing by chaining together multiple commands to perform sophisticated operations. Overall, pipe commands are considered a valuable tool for system administrators and developers.

What is the syntax for using pipe commands in shell scripting?
The syntax for using pipe commands in shell scripting is to use the ?|? symbol to connect multiple commands. For example, ?command1 | command2?.

How does the output of one command serve as the input for the next command in shell scripting?
In shell scripting, the output of one command can be directed as the input for the next command by using the ?|? symbol. For example, ?command1 | command2? directs the output of ?command1? as input to ?command2?.

What symbol is used to link multiple commands together in shell scripting?
The symbol used to link multiple commands together in shell scripting is the ?|? symbol.

How do you utilize pipe commands in shell scripting?
Pipe commands in shell scripting can be used to link multiple commands together. The ?|? symbol is used to connect the commands, allowing the output of one command to serve as the input for the next.

72. How do you debug shell scripts effectively?

Ans: 

How can log files or error output be analyzed for effective debugging?
Analyzing log files or error output provides insights into any issues or errors that occurred during script execution. By examining these logs, developers can identify and resolve problems effectively.

What is the trap command and how can it be used for effective debugging?
The trap command allows developers to catch and handle signals. It enables specifying actions to be taken when a specific signal, such as an interruption, is received. This allows for better control and handling of unexpected events.

How can echo statements be used for effective debugging?
Echo statements can be inserted in the script to print intermediate values. This helps developers understand the flow of the script and identify unexpected or incorrect values causing errors.

What is the "set -x" option and how can it be used for effective debugging?
The "set -x" option enables debugging mode in the script, displaying each command, its output, and variables being used. This provides developers with detailed information to identify errors or issues.

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

Ans: 

What is the purpose of shell variables?
Shell variables are predefined by the shell and hold system information. They are used to store important data such as the user's home directory (e.g., $HOME).

What is the scope of environment variables?
Environment variables are available system-wide and can be accessed by any script or program.

What is the scope of local variables?
Local variables are defined within a script and are only accessible within that script.

What are the three primary types of variables in shell scripting?
The three primary types of variables in shell scripting are local variables, environment variables, and shell variables.

About Author

A technical lead content writer in HKR Trainings with an expertise in delivering content on the market demanding technologies like Networking, Storage & Virtualization,Cyber Security & SIEM Tools, Server Administration, Operating System & Administration, IAM Tools, Cloud Computing, etc. She does a great job in creating wonderful content for the users and always keeps updated with the latest trends in the market. To know more information connect her on Linkedin, Twitter, and Facebook.

Upcoming Shell Scripting Training Certification Online classes

Batch starts on 23rd Mar 2024
Mon - Fri (18 Days) Weekend Timings - 10:30 AM IST
Batch starts on 27th Mar 2024
Mon & Tue (5 Days) Weekday Timings - 08:30 AM IST
Batch starts on 31st Mar 2024
Mon - Fri (18 Days) Weekend Timings - 10:30 AM IST
To Top