Top Interview Questions and Answers on Unix shell scripting ( 2025 )
Below are some common interview questions related to Unix shell scripting, along with detailed answers that can help you understand the concepts better.
1. What is Shell Scripting?
Answer:
Shell scripting is a way to automate tasks in a Unix/Linux operating system by writing a script in the shell language. A shell script is essentially a text file containing a series of commands that the shell can execute. Shell scripts can include commands for file manipulation, program execution, and more. They are often used to simplify complex operations, automate repetitive tasks, and can be written in various shells like Bash, Ksh, and Zsh.
2. How do you create a shell script?
Answer:
To create a shell script, follow these steps:
1. Open a terminal.
2. Use a text editor (like `nano`, `vim`, or `gedit`) to create a new file:
```bash
nano myscript.sh
```
3. At the top of the file, add the shebang line to specify the interpreter:
```bash
#!/bin/bash
```
4. Write the commands you want to execute in the script.
5. Save and exit the editor.
6. Make the script executable using:
```bash
chmod +x myscript.sh
```
7. Run the script:
```bash
./myscript.sh
```
3. What is the purpose of the shebang (`#!`) line in a shell script?
Answer:
The shebang line (`#!`) is used to indicate which interpreter should be used to execute the script. It is typically the first line in a shell script. For example, `#!/bin/bash` tells the operating system to use the Bash shell to interpret the commands in the script. If the script does not have a shebang, it will be executed with the current shell, which may lead to unexpected behavior if the commands are specific to a different shell.
4. How do you pass arguments to a shell script?
Answer:
You can pass arguments to a shell script directly via the command line when you execute it. Inside the script, you can access these arguments using special variables:
- `$0`: The name of the script.
- `$1`, `$2`, ...: The first, second, and subsequent command-line arguments.
- `$#`: The total number of arguments passed.
- `$@`: All arguments as a list.
- `$*`: All arguments as a single word.
Example:
```bash
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Total arguments: $#"
```
Run the script:
```bash
./myscript.sh arg1 arg2 arg3
```
Output:
```
Script name: ./myscript.sh
First argument: arg1
Total arguments: 3
```
5. What are some common control structures used in shell scripting?
Answer:
Common control structures in shell scripting include:
- If-Else Statements:
```bash
if [ condition ]; then
# commands
else
# other commands
fi
```
- For Loops:
```bash
for var in list; do
# commands
done
```
- While Loops:
```bash
while [ condition ]; do
# commands
done
```
- Case Statements:
```bash
case variable in
pattern1)
# commands
;;
pattern2)
# commands
;;
*)
# default commands
;;
esac
```
6. How do you create and handle functions in shell scripting?
Answer:
You can create functions in shell scripts to encapsulate commands for reuse. Here’s the syntax:
```bash
function_name() {
# commands
}
# Example function
greet() {
echo "Hello, $1!"
}
# Calling the function
greet "World"
```
7. How can you read user input in a shell script?
Answer:
You can read user input using the `read` command:
```bash
#!/bin/bash
echo "Enter your name: "
read name
echo "Hello, $name!"
```
8. What is `grep`, and how can it be used in shell scripting?
Answer:
`grep` is a command-line utility used to search for specific patterns within files or input provided to it. It can be used in shell scripts to filter text based on matching patterns.
Example:
To find lines containing "error" in a log file:
```bash
#!/bin/bash
grep "error" logfile.log
```
9. How do you redirect output and errors in a shell script?
Answer:
You can redirect standard output (stdout) and standard error (stderr) in shell scripts using `>`, `>>`, and `2>`. For example:
- To redirect stdout to a file:
```bash
command > output.txt
```
- To append stdout to a file:
```bash
command >> output.txt
```
- To redirect stderr to a file:
```bash
command 2> error.txt
```
- To redirect both stdout and stderr:
```bash
command > output.txt 2>&1
```
10. What are some best practices for writing shell scripts?
Answer:
- Use meaningful variable names.
- Comment your code for clarity.
- Use `set -e` at the beginning to exit on errors.
- Use quotes around variables to prevent word splitting and globbing.
- Validate user inputs.
- Test the script on different environments to ensure compatibility.
By preparing with these questions and answers, you'll be well-equipped to demonstrate your understanding of Unix shell scripting during an interview. Good luck!
These questions cover various aspects of Unix shell scripting, from basic to advanced topics. Understanding these will help prepare for interviews that focus on scripting and automation tasks.
Some advanced interview questions on Unix shell scripting, along with their answers:
1. What is the difference between `>` and `>>` in shell scripting?
- Answer: The `>` operator is used for output redirection and will overwrite the file if it already exists. The `>>` operator is also used for output redirection but will append the output to the end of the file without overwriting its existing content.
2. How can you pass arguments to a shell script?
- Answer: You can pass arguments to a shell script at the command line. Inside the script, these can be accessed using `$1`, `$2`, ..., `$n` where `n` is the positional parameter of the arguments. `$0` refers to the script name itself. For example:
```bash
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
```
3. Explain the use of `set -e` in a shell script.
- Answer: The `set -e` command is used to halt the execution of a script as soon as any command fails (returns a non-zero exit status). This is useful for error handling within scripts, as it prevents cascading failures.
4. What are `trap` commands, and how are they used?
- Answer: The `trap` command is used to specify commands that will be executed when a script receives certain signals or exits for any reason. For example:
```bash
#!/bin/bash
trap 'echo "Script terminated"; exit' SIGINT SIGTERM
echo "Running script..."
sleep 10
```
This script will print a message and exit if it receives `SIGINT` (Ctrl+C) or `SIGTERM`.
5. What does the `exec` command do in shell scripting?
- Answer: The `exec` command replaces the current shell process with the specified command. This means that the shell does not return to its original context after the command has finished executing. It can also redirect file descriptors. For example:
```bash
exec > output.txt
echo "This will go to output.txt"
```
6. How do you check if a directory exists in a shell script?
- Answer: You can use the `-d` flag in an `if` condition to check for the existence of a directory. For example:
```bash
if [ -d "/path/to/directory" ]; then
echo "Directory exists."
else
echo "Directory does not exist."
fi
```
7. Explain the difference between `&&` and `||` in shell scripting.
- Answer: The `&&` operator is a logical AND that allows you to execute the next command only if the previous command succeeded (returned a zero exit status). The `||` operator is a logical OR that allows you to execute the next command only if the previous command failed (returned a non-zero exit status). For example:
```bash
command1 && command2 # command2 executes if command1 succeeds
command1 || command2 # command2 executes if command1 fails
```
8. How can you create a function in a shell script?
- Answer: Functions in shell scripts can be defined with the following syntax:
```bash
my_function() {
echo "Hello, World!"
}
```
You can then call `my_function` to execute its contents.
9. What is the purpose of `readonly` in shell scripting?
- Answer: The `readonly` command is used to mark a variable as constant, which means its value cannot be modified after it has been set. For example:
```bash
readonly var="constant"
var="new_value" # This will cause an error
```
10. Describe process substitution and give an example of its use.
- Answer: Process substitution allows you to treat the output of a command as if it were a file. It is done using `<(command) or >(command)`. For example:
```bash
diff <(ls dir1) <(ls dir2)
```
This command compares the output of `ls` on two directories using `diff`.
11. How can you read and parse a file line by line in a shell script?
- Answer: You can use a `while` loop in conjunction with `read` to read a file line by line, like this:
```bash
while IFS= read -r line; do
echo "$line"
done < "file.txt"
```
12. Explain what a "here document" is in shell scripting.
- Answer: A "here document" (or heredoc) is a way to provide input to a command or script. It allows you to input multiple lines of data directly in the script itself. For example:
```bash
cat <<EOF
This is line 1
This is line 2
EOF
```
13. What does the `basename` command do?
- Answer: The `basename` command is used to extract the filename from a given path. For example:
```bash
filename=$(basename /path/to/file.txt)
echo $filename # Output: file.txt
```
14. How can you use conditional statements in shell scripts?
- Answer: Conditional statements in shell scripting use the `if`, `then`, `elif`, `else`, and `fi` syntax. Here’s an example:
```bash
if [ -f "file.txt" ]; then
echo "File exists."
else
echo "File does not exist."
fi
```
15. What is the purpose of `shift` in shell scripting?
- Answer: The `shift` command is used to shift the positional parameters to the left, effectively discarding `$1`. This allows you to process command-line arguments one by one. After calling `shift`, `$2` becomes `$1`, `$3` becomes `$2`, and so on.