Interview

15 Shell Script Interview Questions and Answers

Prepare for your interview with this guide on shell scripting. Enhance your skills with curated questions and answers for Unix-based system automation.

Shell scripting is a powerful tool for automating tasks in Unix-based systems. It allows users to write scripts that can manage system operations, automate repetitive tasks, and streamline complex workflows. With its ability to interact directly with the operating system, shell scripting is an essential skill for system administrators, developers, and IT professionals.

This article provides a curated selection of shell scripting questions and answers to help you prepare for your upcoming interview. By familiarizing yourself with these questions, you will gain a deeper understanding of shell scripting concepts and enhance your problem-solving abilities, making you a more competitive candidate.

Shell Script Interview Questions and Answers

1. Write a script that reads a file line by line and prints each line with its line number.

To read a file line by line and print each line with its line number, use a while loop with the read command. This ensures each line is processed individually, and the line number is incremented accordingly.

#!/bin/bash

filename="yourfile.txt"
line_number=1

while IFS= read -r line
do
  echo "$line_number: $line"
  ((line_number++))
done < "$filename"

2. Create a script that copies all .txt files from one directory to another.

To copy all .txt files from one directory to another, use the following script:

#!/bin/bash

# Source directory
src_dir="/path/to/source/directory"

# Destination directory
dest_dir="/path/to/destination/directory"

# Copy all .txt files from source to destination
cp "$src_dir"/*.txt "$dest_dir"

This script sets the source and destination directories and uses the cp command to copy all .txt files.

3. Write a script that checks if a given number is even or odd.

To check if a number is even or odd, use the modulo operator. If the remainder is 0 when divided by 2, the number is even; otherwise, it’s odd.

#!/bin/bash

read -p "Enter a number: " number

if [ $((number % 2)) -eq 0 ]; then
    echo "The number $number is even."
else
    echo "The number $number is odd."
fi

4. Write a script that takes three command-line arguments and prints them in reverse order.

To print three command-line arguments in reverse order, use:

#!/bin/bash

echo "$3 $2 $1"

This script uses positional parameters to access and print the arguments in reverse.

5. Create a script that replaces all occurrences of a substring in a string with another substring.

To replace all occurrences of a substring in a string with another substring, use the sed command:

#!/bin/bash

original_string="Hello world, welcome to the world of shell scripting."
substring_to_replace="world"
new_substring="universe"

# Using sed to replace all occurrences of the substring
modified_string=$(echo "$original_string" | sed "s/$substring_to_replace/$new_substring/g")

echo "$modified_string"

6. Write a script that lists all running processes and allows the user to kill a selected process.

#!/bin/bash

# List all running processes
ps -e

# Prompt the user to enter the PID of the process to kill
echo "Enter the PID of the process you want to kill:"
read pid

# Kill the selected process
kill -9 $pid

echo "Process $pid has been killed."

7. Write a script that checks if a file exists and displays an error message if it does not.

To check if a file exists and display an error message if it does not, use:

#!/bin/bash

FILE="path/to/your/file.txt"

if [ -f "$FILE" ]; then
    echo "$FILE exists."
else
    echo "Error: $FILE does not exist."
fi

8. Develop a script that uses a regular expression to validate an email address format.

To validate an email address format using a regular expression, use:

#!/bin/bash

validate_email() {
    local email=$1
    local regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    
    if [[ $email =~ $regex ]]; then
        echo "Valid email address."
    else
        echo "Invalid email address."
    fi
}

# Example usage
validate_email "[email protected]"
validate_email "invalid-email"

This script uses a regex pattern to ensure the email address contains valid characters, an “@” symbol, a domain name, and a top-level domain.

9. Write a script that redirects the output of a command to a file and appends it if the file already exists.

To redirect the output of a command to a file and append it if the file already exists, use the >> operator:

#!/bin/bash

# Command whose output needs to be redirected
echo "This is a new line of text" >> output.txt

This appends the text to output.txt, creating the file if it doesn’t exist.

10. Describe techniques you would use to optimize a shell script for better performance.

To optimize a shell script for better performance, consider these techniques:

  • Minimize External Commands: Use built-in shell commands and avoid unnecessary external commands.
  • Use Efficient Loops: Prefer while or for loops over cat or grep pipelines.
  • Reduce I/O Operations: Minimize read and write operations. Use redirection and avoid repeatedly opening and closing files.
  • Leverage Shell Built-ins: Use built-in shell features like test and [[ ]] for conditionals.
  • Parallel Processing: Use background processes and the wait command to run tasks in parallel.
  • Profile and Benchmark: Use tools like time and strace to profile the script and identify bottlenecks.
  • Optimize Regular Expressions: Use efficient regular expressions and avoid unnecessary complexity in pattern matching.
  • Use Arrays: When dealing with lists of items, use arrays instead of repeatedly calling commands in a loop.

11. Discuss security best practices you would follow when writing shell scripts.

When writing shell scripts, follow these security best practices:

  • Input Validation: Validate and sanitize user inputs to prevent injection attacks.
  • Least Privilege Principle: Run the script with the minimum privileges required.
  • Use Absolute Paths: Specify absolute paths for commands and files to avoid ambiguity.
  • Handle Sensitive Data Securely: Avoid hardcoding sensitive information. Use environment variables or secure vaults.
  • Check Exit Status: Always check the exit status of commands to handle errors gracefully.
  • Limit External Command Usage: Minimize the use of external commands and prefer built-in shell features.
  • Log Actions: Implement logging to track script actions and potential security events.
  • Regular Updates: Keep the shell and related tools updated for the latest security patches.

12. Write a script that demonstrates the use of a subshell to execute commands in a separate environment.

A subshell allows you to execute commands in an isolated environment. Here’s an example:

#!/bin/bash

# Define a variable in the parent shell
PARENT_VAR="I am the parent"

# Start a subshell
(
    # Define a variable in the subshell
    SUBSHELL_VAR="I am the subshell"
    
    # Print the variables
    echo "Inside subshell: PARENT_VAR = $PARENT_VAR"
    echo "Inside subshell: SUBSHELL_VAR = $SUBSHELL_VAR"
    
    # Modify the parent variable
    PARENT_VAR="Modified by subshell"
    
    # Print the modified parent variable
    echo "Inside subshell: Modified PARENT_VAR = $PARENT_VAR"
)

# Print the variables in the parent shell
echo "Outside subshell: PARENT_VAR = $PARENT_VAR"
echo "Outside subshell: SUBSHELL_VAR = $SUBSHELL_VAR"

In this script, the subshell is created using parentheses (). Changes made inside the subshell do not affect the parent shell.

13. Write a script that uses awk to print the second column of a CSV file.

To print the second column of a CSV file using awk, use:

#!/bin/bash
awk -F',' '{print $2}' input.csv

The -F',' option specifies the field separator as a comma, typical for CSV files. The {print $2} command tells awk to print the second column.

14. Describe how you would handle errors in a shell script to ensure robustness.

Error handling in shell scripts ensures the script behaves as expected even when something goes wrong. Here are some strategies:

  • Exit Statuses: Every command returns an exit status. A status of 0 indicates success, while any non-zero status indicates an error. Check the exit status using $? and take appropriate action.
  • set -e: This command makes the script exit immediately if any command returns a non-zero status.
  • Trap Command: The trap command can catch signals and errors, allowing you to execute cleanup commands or custom error messages.
  • Conditional Statements: Use if, else, and elif statements to handle different error conditions.

Example:

#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Function to handle errors
error_handler() {
    echo "Error occurred in script at line: $1"
    exit 1
}

# Trap errors and call error_handler
trap 'error_handler $LINENO' ERR

# Example command that might fail
cp source_file.txt destination_file.txt

echo "Script executed successfully"

15. Discuss methods to monitor and improve the performance of a shell script.

Monitoring the performance of a shell script can be achieved using various tools and techniques:

  • Time Command: The time command measures the execution time of a script or command.
  • Profiling Tools: Tools like strace and ltrace trace system calls and library calls, respectively.
  • Logging: Add logging statements within the script to track execution flow and time taken for specific sections.

Improving performance involves several strategies:

  • Optimize Loops: Minimize the use of loops and ensure they are efficient.
  • Use Built-in Commands: Prefer built-in shell commands over external commands as they are generally faster.
  • Parallel Execution: Use background processes or tools like xargs and GNU parallel to execute tasks in parallel.

Example:

#!/bin/bash

# Monitoring with time command
time {
    # Example of optimizing a loop
    for i in {1..1000}; do
        echo $i
    done

    # Example of using built-in commands
    if [[ -f "file.txt" ]]; then
        echo "File exists"
    fi

    # Example of parallel execution
    find . -type f -print0 | xargs -0 -n 1 -P 4 grep "search_term"
}
Previous

10 GPU Architecture Interview Questions and Answers

Back to Interview
Next

10 Java Spark Interview Questions and Answers