Interview

15 Unix Shell Scripting Interview Questions and Answers

Prepare for your next technical interview with our comprehensive guide on Unix Shell Scripting, featuring common questions and detailed answers.

Unix Shell Scripting is a powerful tool for automating tasks and managing system operations. It is widely used in various domains such as system administration, data processing, and software development. The ability to write efficient shell scripts can significantly enhance productivity by automating repetitive tasks and streamlining complex workflows. Unix Shell Scripting is known for its flexibility and robustness, making it an essential skill for professionals working in environments that rely on Unix-based systems.

This article provides a curated selection of Unix Shell Scripting questions and answers designed to help you prepare for technical interviews. By familiarizing yourself with these questions, you will gain a deeper understanding of key concepts and practical applications, positioning yourself as a strong candidate in the job market.

Unix Shell Scripting Interview Questions and Answers

1. Write a script that takes a filename as an argument and prints the number of lines in the file.

To write a script that takes a filename as an argument and prints the number of lines in the file, you can use the following shell script:

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "No filename provided"
    exit 1
fi

filename=$1

if [ ! -f "$filename" ]; then
    echo "File not found!"
    exit 1
fi

line_count=$(wc -l < "$filename")
echo "Number of lines in $filename: $line_count"

2. Write a script to find and replace a string in a file.

To find and replace a string in a file, use the sed command, a powerful utility for parsing and transforming text in Unix-based systems.

Here is a simple script to find and replace a string in a file:

#!/bin/bash

# Variables
file="example.txt"
search="old_string"
replace="new_string"

# Using sed to find and replace
sed -i "s/$search/$replace/g" "$file"

In this script:
file is the name of the file where the operation will be performed.
search is the string you want to find.
replace is the string you want to replace the search string with.
– The sed command with the -i option edits the file in place, and the s command is used for substitution. The g flag ensures all occurrences are replaced.

3. Write a script that checks if a given directory exists and prints an appropriate message.

To check if a given directory exists and print an appropriate message, use the -d flag in a simple script:

#!/bin/bash

DIRECTORY=$1

if [ -d "$DIRECTORY" ]; then
    echo "Directory $DIRECTORY exists."
else
    echo "Directory $DIRECTORY does not exist."
fi

4. Write a script that handles errors when trying to read a non-existent file.

Error handling is important for creating reliable scripts. When attempting to read a non-existent file, check if the file exists before trying to read it using conditional statements like if and else.

Example:

#!/bin/bash

filename="non_existent_file.txt"

if [ -e "$filename" ]; then
    cat "$filename"
else
    echo "Error: File '$filename' does not exist."
fi

In this script, the if statement checks if the file exists using the -e flag. If it does, the file is read using the cat command. Otherwise, an error message is printed.

5. Write a script to validate an email address using regular expressions.

To validate an email address using regular expressions, you can use tools like grep or sed. Regular expressions provide a way to match patterns in strings.

Here is a simple script using grep to validate an email address:

#!/bin/bash

email="$1"

if echo "$email" | grep -E -q "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"; then
    echo "Valid email address"
else
    echo "Invalid email address"
fi

In this script, the regular expression is used to match a typical email address format. The grep -E -q command checks if the input email matches the pattern.

6. Write a script to execute multiple commands in parallel and wait for all of them to finish.

To execute multiple commands in parallel and wait for all of them to finish, use background processes and the wait command. Background processes are initiated by appending an ampersand (&) to the command.

Example:

#!/bin/bash

# Start multiple commands in the background
command1 &
command2 &
command3 &

# Wait for all background processes to finish
wait

echo "All commands have finished executing."

In this example, command1, command2, and command3 are executed in parallel. The wait command ensures the script waits for all these processes to complete.

7. Write a script that defines and uses a custom function to calculate the factorial of a number.

You can define a custom function to calculate the factorial of a number. A factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n.

Example:

#!/bin/bash

factorial() {
    local n=$1
    local result=1

    for (( i=2; i<=n; i++ ))
    do
        result=$((result * i))
    done

    echo $result
}

# Usage
number=5
echo "The factorial of $number is $(factorial $number)"

8. Write a script to solve a complex problem, such as parsing a log file and generating a summary report.

To parse a log file and generate a summary report, use a script to read the log file, extract relevant information, and summarize it.

#!/bin/bash

# Define the log file
LOG_FILE="server.log"

# Initialize counters
total_requests=0
error_count=0

# Read the log file line by line
while IFS= read -r line
do
    total_requests=$((total_requests + 1))
    
    # Check if the line contains an error
    if [[ "$line" == *"ERROR"* ]]; then
        error_count=$((error_count + 1))
    fi
done < "$LOG_FILE"

# Generate the summary report
echo "Summary Report"
echo "--------------"
echo "Total Requests: $total_requests"
echo "Total Errors: $error_count"

9. Explain how to set and use environment variables in a script.

Environment variables store information that can be used by the operating system and applications. They are key-value pairs that can influence the behavior of processes.

To set an environment variable, use the export command. To access the value, use the $ symbol followed by the variable name.

Example:

#!/bin/bash

# Setting an environment variable
export MY_VAR="Hello, World!"

# Using the environment variable
echo $MY_VAR

# Another example of using an environment variable
export PATH=$PATH:/new/path
echo $PATH

In this example, MY_VAR is set to “Hello, World!” and then accessed using $MY_VAR. The PATH variable is also modified to include a new directory.

10. Explain techniques to optimize the performance of a shell script.

To optimize the performance of a shell script, consider the following techniques:

– Minimize external commands by using built-in shell commands and functions.
– Use efficient loops and consider tools like awk or sed for processing large files.
– Utilize background processes and parallel execution to perform tasks concurrently.
– Avoid unnecessary subshells and use built-in shell features.
– Optimize I/O operations by combining multiple read/write operations.
– Profile and benchmark using tools like time and strace.
– Use shell built-ins instead of external utilities.
– Manage memory usage by avoiding large datasets in variables.

11. Explain security best practices to follow while writing shell scripts.

When writing shell scripts, follow security best practices to prevent vulnerabilities:

– Validate and sanitize user inputs to prevent injection attacks.
– Run scripts with the minimum privileges required.
– Specify absolute paths for commands and files.
– Avoid hardcoding sensitive information; use environment variables or secure vaults.
– Check the exit status of commands to handle errors gracefully.
– Use secure protocols like SSH or HTTPS for data transmission.
– Restrict access to script files using appropriate file permissions.
– Implement logging to monitor script activities.

12. Describe how to integrate your shell scripts with a version control system like Git.

Integrating your shell scripts with a version control system like Git involves initializing a Git repository, adding your scripts, and committing changes. Use git init to initialize, git add to stage files, and git commit to save changes. To share or back up your scripts, push commits to a remote repository using git push.

13. Explain how to manage file permissions within a script.

In Unix, file permissions determine who can read, write, or execute a file. Use the chmod command to change permissions, chown to change the file owner, and chgrp to change the group ownership.

Example:

#!/bin/bash

# Change file permissions to read, write, and execute for the owner, and read and execute for the group and others
chmod 755 myfile.txt

# Change the owner of the file to 'user'
chown user myfile.txt

# Change the group of the file to 'group'
chgrp group myfile.txt

14. Describe how to schedule a script to run periodically using cron jobs.

Cron jobs allow users to schedule scripts or commands to run at specified intervals. The cron daemon reads the crontab files and executes the scheduled tasks.

To schedule a script using cron jobs, edit the crontab file. Each line represents a scheduled task and follows a specific syntax:

* * * * * /path/to/script.sh

The five asterisks represent the time and date fields: minute, hour, day of the month, month, and day of the week.

For example, to schedule a script to run every day at 2:30 AM, add the following line to your crontab file:

30 2 * * * /path/to/script.sh

To edit the crontab file, use:

crontab -e

15. Explain how to handle Unix signals in a shell script.

In Unix shell scripting, signals notify a process that a particular event has occurred. Common signals include SIGINT (interrupt from keyboard), SIGTERM (termination signal), and SIGHUP (hangup detected on controlling terminal). Handling these signals allows a script to perform cleanup tasks before exiting.

To handle signals, use the trap command to specify a command to be executed when the shell receives a specific signal.

Example:

#!/bin/bash

# Function to handle cleanup
cleanup() {
    echo "Cleaning up before exit..."
    # Perform cleanup tasks here
    exit 0
}

# Trap SIGINT and SIGTERM signals
trap cleanup SIGINT SIGTERM

# Main script logic
echo "Script is running. Press Ctrl+C to interrupt."
while true; do
    sleep 1
done

In this example, the trap command is used to catch SIGINT and SIGTERM signals and execute the cleanup function. The script runs an infinite loop, and when interrupted, the cleanup function is called.

Previous

10 Excel VBA Interview Questions and Answers

Back to Interview
Next

10 Conversion Rate Optimization Interview Questions and Answers