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.
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.
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"
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.
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
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.
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"
#!/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."
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
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.
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.
To optimize a shell script for better performance, consider these techniques:
When writing shell scripts, follow these security best practices:
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.
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.
Error handling in shell scripts ensures the script behaves as expected even when something goes wrong. Here are some strategies:
$?
and take appropriate action.trap
command can catch signals and errors, allowing you to execute cleanup commands or custom error messages.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"
Monitoring the performance of a shell script can be achieved using various tools and techniques:
time
command measures the execution time of a script or command.strace
and ltrace
trace system calls and library calls, respectively.Improving performance involves several strategies:
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" }