Automating repetitive processes like software deployments, data processing, and system administration requires shell scripting. Proficiency in Unix/Linux shell scripting is still very important in today’s technologically advanced world. Here are 40 Unix Shell scripting interview questions and answers for freshers and experienced. Kickstart your automation career with our Unix Shell Scripting course syllabus.
Unix Shell Scripting Interview Questions and Answers for Freshers
Here are the basic Unix Shell Scripting interview questions and answers:
1. What is a Unix Shell Script?
A text file containing a series of commands for an operating system (OS) based on Unix is called a shell script. Because it combines a series of commands from a file that would otherwise need to be put in one at a time into a single script, it is known as a shell script.
2. What are the types of shells available in Unix?
The various types of Unix Shells are:
- Bourne Shell (sh)
- Bash (Bourne Again Shell)
- C Shell (csh)
- Korn Shell (ksh)
- Z Shell (zsh)
3. How do you execute a shell script?
A shell script can be run by:
- Making it executable: chmod +x script.sh and then running it: ./script.sh
- Using the shell directly: sh script.sh or bash script.sh
4. What is the shebang line?
A “shebang line” is the first line of a script file that begins with the characters “#!” It tells the operating system which program to use to run the script by supplying the path to the interpreter program. This serves as a means of defining the script’s execution environment.
Syntax: Always starts with “#!”.
Purpose: To specify which application should be used to execute the script.
Example: #!/bin/bash It instructs the system to execute the script using the Bash interpreter.
5. How do you comment in a shell script?
The # sign can be used to add comments in a shell script. The shell ignores anything on a line that comes after #.
6. What is the difference between $0, $1, and $2 in a shell script?
Some “magic” variables from the environment are accessible to shell scripts: $0 is the script’s name. $1: The script receives the first argument. $2: The script received the second parameter.
- $0: It refers to the script’s name.
- $1: It refers to the first argument passed to the script.
- $2: It refers to the second argument passed to the script.
7. How do you pass arguments to a shell script?
When running the script, the following arguments are passed:./script.sh arg1 arg2. $1, $2, etc. can be used to access them inside the script.
By specifying arguments as a space-delimited list after the script file name, you can give them to the script when it runs. The first argument in the command line is referred to by the $1 variable inside the script, the second by the $2 variable, and so on. The current script is referenced by the variable $0.
Recommended: Unix Shell Scripting Online Course Program.
8. What is the purpose of the $? variable?
- $?: The status of the previous command’s exit.
- $$: The current shell’s process ID.
- $!: The most recent background command’s process ID.
9. How do you check if a command was successful?
A useful tool for determining the state of the most recent command that was run, particularly in scripting, is the $? operator. By knowing how to understand its values, you can write scripts that are more resilient and error-tolerant since you may make judgments on whether or not the prior operation was successful.
Example:
command
if [ $? -eq 0 ]; then
echo “Success”
else
echo “Failed”
fi
10. State the difference between = and == in shell scripting.
- To compare strings, we can use =.
- Although it is not POSIX-compliant, == is also used in Bash for string comparison.
11. How can a shell script compare strings?
In bash, the simplest method of comparing two strings is to see if they are identical. Double equal signs (==) for equality and the well-known “not equal” operator combination (!=) are used for this.
Use the = operator:
if [ “$string1” = “$string2” ]; then
echo “Strings are equal”
fi
12. How do you compare numbers in a shell script?
Relational operators like -eq, -ne, -gt, -lt, -ge, and -le can be used to compare integers in Bash. You can assess the relationship between two numbers by using these operations. This example uses the -gt (greater than) operator to compare two numbers, num1 and num2.
Use -eq, -ne, -gt, -lt, -ge, -le:
Example:
if [ $num1 -eq $num2 ]; then
echo “Numbers are equal”
fi
13. What is the purpose of the test command?
In operating systems similar to Unix, the “test” command evaluates expressions and conditions, essentially determining whether a statement is true or false.
The results of these evaluations can be used to make decisions within shell scripts. It can be used to check for the existence of files, compare strings, check numerical values, and perform logical operations, returning a status code that indicates whether the expression is true or false.
Syntax: Most commonly used with square brackets “[]” as a shorthand, like [ expression ].
14. What is the difference between [ ] and [[ ]] in shell scripting?
Both of them are employed for testing purposes. Since [[ is a keyword rather than a built-in, it can provide a longer test. Bash attempts to reroute the file b to the command [a] in the first example, which results in an error. In fact, the second example does arithmetic comparison as expected.
[ ]: The classic test command (POSIX-compliant).
[[ ]]: It is an additional functionality like pattern matching and logical operators are supported by this Bash extension.
Learn fundamentals with our C and C++ training in Chennai.
15. In a shell script, how do you concatenate strings?
The addition assignment operator (+=) is used to connect two or more strings to create a concatenated string. Using one or more variables to join strings is made feasible by this operator.
Example:
str1=”Hello”
str2=”World”
result=”$str1 $str2″
echo $result
16. How do you check if a file exists in a shell script?
The -f parameter determines if the supplied filename is a regular file and if it exists. Alternatively, we can use the -d switch to test for directories. The -e flag can be used to test for both files and directories. By entering the man test into the terminal, you may visit the test’s manual page, which has further details.
Example: Use the -f flag:
if [ -f “$file” ]; then
echo “File exists”
fi
17. How do you check if a directory exists in a shell script?
Test -d is an option (see man test). -d file True if the file is a directory and it exists. Note: The test command is universal across shell scripts since it is equivalent to the conditional phrase [ (see: man [ ).
Example: Use the -d flag:
if [ -d “$dir” ]; then
echo “Directory exists”
fi
18. What is the purpose of the export command?
In a Linux shell environment, you can share settings between programs running in the same terminal session by using the “export” command to mark a variable as accessible to child processes. This effectively turns the variable into a global variable that can be used by any program that is spawned from the current shell session.
19. In a shell script, how do you read user input?
Use the “read” command to read user input in a shell script. This lets you store the user’s input in a variable that you can use later in your script. For instance, echo “Enter your name: “; read name will ask the user to enter their name and save it in the “name” variable.
Example: Use the read command:
read -p “Enter your name: ” name
echo “Hello, $name”
20. What is the difference between $* and $@?
While the “$@” special parameter accepts the full list and divides it into distinct arguments, the “$*” special parameter takes the entire list as a single argument with spaces between.
- $*: All arguments are treated as a single string.
- $@: Every argument is handled as a distinct string.
Finetune your skills with our C and C++ interview questions and answers.
Unix Shell Scripting Interview Questions and Answers for Experienced
Here are the Unix Shell Scripting advanced interview questions and answers:
1. How do you use arrays in shell scripting?
To generate an array, the simplest method is to use an array literal.
Syntax: const array_name = [item1, item2,…];
Frequently, arrays are declared using the const keyword.
Example: Declare and use arrays like this:
arr=(“apple” “banana” “cherry”)
echo ${arr[1]} # Outputs “banana”
2. What is the purpose of the trap command?
In shell scripting, you can “catch” and react to specific system events that occur during a script’s execution by using the “trap” command to define actions to be taken when a specific system signal is received. This enables a script to gracefully handle events like interruptions (like Ctrl+C) or unexpected termination by executing custom code in response to the signal.
3. How do you debug a shell script?
“Echo” is the simplest step in script debugging. To see if the output section is capturing the correct values or not, you can “echo” the command that you are using the variables on. Likewise, commands can also be written in this format.
To enable debugging, execute the script using bash -x script.sh or use set -x.
4. What is a “here document”?
A HereDoc is a file literal or multiline string that is used to provide input streams to other programs and instructions. HereDocs are particularly helpful for rerouting several commands at once, which makes Bash scripts more readable and organized.
Example:
cat <<EOF
This is a
multiline string
EOF
5. How do you redirect output to a file?
We can redirect output to a file using > to overwrite or >> to append:
echo “Hello” > file.txt
echo “World” >> file.txt
6. What is the purpose of the exec command?
By replacing the current shell process with a new one, the “exec” command in Unix enables you to run a command without establishing a new, independent process.
This allows you to run a program directly within the shell environment and makes better use of its resources. It “takes over” the current shell to run a new program rather than starting a new one.
7. How do you handle command-line options in a shell script?
When some command-line parameters are optional, you can set default values so that your script will still work even if they are not supplied. You can check to see if the command-line parameters are supplied after using variables to hold the default values.
Example: Use getopts:
while getopts “a:b:” opt; do
case $opt in
a) arg1=”$OPTARG” ;;
b) arg2=”$OPTARG” ;;
esac
done
8. What is the difference between && and ||?
Comprehending their distinctions and attributes enables their efficient application in diverse programming contexts. However, && is helpful to make sure that every condition is satisfied. || is perfect for giving the default values or making sure at least one condition is met.
- &&: It executes the next command only if the previous one succeeds.
- ||: It executes the next command only if the previous one fails.
9. How do you use awk in a shell script?
Awk is a text processing tool. It is simplest to include a short program in the command that executes awk, such as this: awk’program’input-file1 input-file2 … It is typically more convenient to run a lengthy program using a command and store it in a file.
Example:
echo “Hello World” | awk ‘{print $2}’ # Outputs “World”
Learn from anywhere with our full stack developer online training program.
10. How do you use sed in a shell script?
The sed command functions similarly to a filter. It reads, edits, and outputs text to standard output after reading it from standard input or from files named on the command line (in this case, chapter 1). It doesn’t change the original file like most editors do.
Example:
echo “Hello World” | sed ‘s/World/Unix/’ # Outputs “Hello Unix”
11. How do you loop through files in a directory?
Writing a recursive function that takes the path of the target directory as a starting parameter, iterates over each entry of the current directory, and executes itself whenever that entry is a directory is one way to loop through the files in a directory and its subdirectories.
Example: Use a for loop:
for file in /path/to/dir/*; do
echo “$file”
done
12. How do you find files in a directory?
Use the search box located to the right of the address bar when you launch File Explorer to look for files. To launch File Explorer, tap or click. Every folder and subfolder in the library or folder you are now browsing is searched. The Search Tools tab opens when you tap or click inside the search field.
Example: Use the find command:
find /path/to/dir -name “*.txt”
13. How do you delete a file in a shell script?
In bash, you use the rm command and the file name to remove a file, for example, rm myfile.txt. The file’myfile.txt’ has been deleted in this example using the rm command.
Example: Use the rm command:
rm file.txt
14. How do you create a directory in a shell script?
This command’s fundamental form is mkdir {dir}, where {dir} is replaced with the directory name you want. Keep in mind that the majority of Linux filesystems are case-sensitive before creating any directories or files.
Example: Use the mkdir command:
mkdir dirname
15. How do you check the size of a file?
We can check the size of a file using the du or wc command:
Example:
du -h file.txt
wc -c file.txt
16. How do you run a process in the background?
Put an ampersand (&) at the end of the command name you use to launch a process if you want it to operate in the background. Daemon works. Unattended processes are known as daemons.
Example: Use &:
sleep 10 &
17. How do you kill a process?
In Unix, you can use either the kill command or the killall command to terminate a process. The xkill utility can also be used to terminate GUI processes.
Example: Use the kill command:
kill PID
18. How do you check running processes?
We can use the command “tasklist” in the Command Prompt on Windows to view running processes via text output.
To check running processes on a computer, open the Task Manager (typically accessed by pressing Ctrl + Shift + Esc) and navigate to the “Processes” tab. This will display a list of all currently active processes on your system.
Example: Use the ps command:
ps aux
19. What is the purpose of the nohup command?
“No hang up” is what the POSIX command nohup means. Its goal is to carry out a command that, by ignoring the HUP (hangup) signal, continues to run after the user logs out. “nohup” allows a process to continue running after the user logs out.
20. How do you schedule tasks in Unix?
The main tool for scheduling tasks in Unix is the “cron” utility, which lets you set deadlines for running scripts or commands by editing a file called “crontab” with the command “crontab -e” in your terminal. This is also known as “cron job” setup, where you set up the time intervals and the command to run at those times.
Example:
Use cron:
crontab -e
Add a line like:
* * * * * /path/to/script.sh
Recommended: Perl Training in Chennai.
Conclusion
These top 40 Unix Shell Scripting interview questions and answers offered here cover a wide range of subjects, from basic ideas to sophisticated methods, making sure you are ready for interviews and actual scripting difficulties. You may master Unix shell scripting and successfully handle scripting problems in professional settings and interviews by putting these ideas into practice and using them in real-world projects with our Unix Shell Scripting training in Chennai.