Interview

15 Linux Shell Scripting Interview Questions and Answers

Prepare for your next technical interview with our comprehensive guide on Linux shell scripting, featuring practical questions and answers.

Linux shell scripting is a powerful tool for automating tasks and managing system operations. It allows users to write scripts that can execute commands, manipulate files, and perform complex operations with ease. Shell scripting is essential for system administrators, developers, and IT professionals who need to streamline workflows and enhance productivity.

This article provides a curated selection of interview questions and answers focused on Linux shell scripting. By studying these examples, you will gain a deeper understanding of key concepts and practical skills, helping you to confidently tackle technical interviews and demonstrate your proficiency in shell scripting.

Linux Shell Scripting Interview Questions and Answers

1. Write a script to create a new directory and move all .txt files from the current directory into this new directory.

To create a new directory and move all .txt files from the current directory into this new directory, use the mkdir command to create the directory and the mv command to move the files.

#!/bin/bash

# Create a new directory named 'new_directory'
mkdir new_directory

# Move all .txt files to the new directory
mv *.txt new_directory/

2. Write a function in a script that takes two arguments and returns their sum.

In shell scripting, you can write a function to take two arguments and return their sum. Here is an example:

#!/bin/bash

sum() {
    local num1=$1
    local num2=$2
    echo $((num1 + num2))
}

result=$(sum 5 10)
echo "The sum is: $result"

3. Write a script to list all running processes and save the output to a file.

To list all running processes and save the output to a file, use the ps command. Redirect the output to a file to save the list of running processes.

Example:

#!/bin/bash

# List all running processes and save the output to a file
ps -e > processes.txt

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

When attempting to read a non-existent file, handle the error to prevent the script from crashing. Use conditional statements and error messages.

Example:

#!/bin/bash

filename="non_existent_file.txt"

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

5. Write a script to find and delete all empty files in a directory.

To find and delete all empty files in a directory, use the find command. Specify a size of 0 to identify empty files and use the -exec option to delete them.

#!/bin/bash

# Directory to search for empty files
directory="/path/to/directory"

# Find and delete all empty files
find "$directory" -type f -size 0 -exec rm -f {} \;

echo "All empty files in $directory have been deleted."

6. Write a script to search for a pattern in a file using regular expressions.

Regular expressions are useful for searching and manipulating text. Use the grep command to search for patterns in files.

Example:

#!/bin/bash

# Define the pattern to search for
pattern="your_pattern_here"

# Define the file to search in
file="your_file_here"

# Use grep to search for the pattern in the file
grep "$pattern" "$file"

7. Write a script to run two commands simultaneously and wait for both to finish.

To run two commands simultaneously and wait for both to finish, use background processes and the wait command.

Example:

#!/bin/bash

# Run the first command in the background
command1 &
# Capture the process ID of the first command
pid1=$!

# Run the second command in the background
command2 &
# Capture the process ID of the second command
pid2=$!

# Wait for both commands to finish
wait $pid1
wait $pid2

echo "Both commands have finished."

8. Write a script to check if a website is reachable by pinging its URL.

To check if a website is reachable by pinging its URL, use the ping command. Send a specified number of ping requests and check the response.

Example:

#!/bin/bash

URL=$1
PING_COUNT=4

if ping -c $PING_COUNT $URL > /dev/null 2>&1; then
    echo "The website $URL is reachable."
else
    echo "The website $URL is not reachable."
fi

9. Write a script to automate the backup of a directory to a remote server.

To automate the backup of a directory to a remote server, use rsync and cron. rsync efficiently transfers files, and cron schedules the script.

Example:

#!/bin/bash

# Variables
SOURCE_DIR="/path/to/local/directory"
DEST_USER="remote_user"
DEST_HOST="remote_host"
DEST_DIR="/path/to/remote/directory"
LOG_FILE="/path/to/logfile.log"

# Rsync command to sync the directory
rsync -avz --delete $SOURCE_DIR $DEST_USER@$DEST_HOST:$DEST_DIR >> $LOG_FILE 2>&1

To automate this script, add a cron job to run it at regular intervals.

10. Write a script to parse a CSV file and extract specific columns.

Parsing a CSV file and extracting specific columns can be done using awk.

Example:

#!/bin/bash

# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <csv_file> <column1> <column2>"
    exit 1
fi

csv_file=$1
column1=$2
column2=$3

# Use awk to extract the specified columns
awk -F, -v col1="$column1" -v col2="$column2" '{print $col1, $col2}' "$csv_file"

11. Write a script to solve a complex problem, such as finding the top 10 most frequently occurring words in a large text file.

To find the top 10 most frequently occurring words in a large text file, use a combination of tr, sort, uniq, and head.

#!/bin/bash

# Check if a file is provided as an argument
if [ -z "$1" ]; then
  echo "Usage: $0 filename"
  exit 1
fi

# Process the file to find the top 10 most frequently occurring words
cat "$1" | tr -cs '[:alnum:]' '[\n*]' | tr '[:upper:]' '[:lower:]' | sort | uniq -c | sort -nr | head -n 10

12. Describe how you would schedule a script to run periodically using cron jobs.

Cron jobs schedule scripts or commands to run at specified intervals. The cron daemon checks the crontab file for scheduled tasks. Each user has their own crontab file.

To schedule a script, edit the crontab file using the crontab command. The basic syntax of a cron job entry is:

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

Each asterisk represents a time field: minute, hour, day of the month, month, and day of the week. Replace the asterisks with specific values or ranges to schedule the script.

Example:

To schedule a script to run every day at 2:30 AM, add the following entry to the crontab file:

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

Edit the crontab file with:

crontab -e

13. Write a script that handles Unix signals like SIGINT.

In Unix-like systems, signals notify a process of specific events. SIGINT is sent when a user interrupts a process with Ctrl+C. Handling signals ensures the script can perform cleanup tasks or exit gracefully.

Example of handling SIGINT:

#!/bin/bash

# Function to handle SIGINT
handle_sigint() {
    echo "SIGINT received. Exiting gracefully..."
    exit 0
}

# Trap SIGINT and call the handle_sigint function
trap 'handle_sigint' SIGINT

# Simulate a long-running process
echo "Script is running. Press Ctrl+C to interrupt."
while true; do
    sleep 1
done

14. Describe how you would integrate your shell scripts with a version control system like Git.

Integrating shell scripts with Git involves versioning, tracking, and managing scripts. Initialize a Git repository with git init, add scripts with git add, and commit them with git commit -m "Your commit message". Push commits to a remote repository with git push. Set up a remote repository with git remote add origin <repository_url>.

Structure your repository for easy management. Use directories for different types of scripts or projects. Use .gitignore to exclude certain files or directories from being tracked.

15. Describe some security best practices you would follow when writing shell scripts.

When writing shell scripts, follow security best practices to prevent vulnerabilities. Here are some key practices:

  • Input Validation: Validate and sanitize user inputs to prevent injection attacks. Use commands like grep, sed, or awk to filter inputs.
  • Use Quoting: Properly quote variables to prevent word splitting and globbing issues. For example, use "$variable" instead of $variable.
  • Least Privilege Principle: Run the script with the minimum privileges required. Avoid using the root account unless necessary.
  • Secure Temporary Files: Use secure methods to create temporary files, such as mktemp, to avoid race conditions and unauthorized access.
  • Handle Sensitive Data Carefully: Avoid hardcoding sensitive information like passwords in the script. Use environment variables or secure vaults to manage sensitive data.
  • Check Exit Status: Always check the exit status of commands to handle errors appropriately. Use set -e to exit the script on any command failure.
  • Logging and Monitoring: Implement logging to monitor script activities and detect any suspicious behavior. Ensure logs do not contain sensitive information.

Example of input validation and quoting:

#!/bin/bash

# Input validation
if [[ ! "$1" =~ ^[0-9]+$ ]]; then
  echo "Error: Input must be a number."
  exit 1
fi

# Proper quoting
filename="$1_file.txt"
echo "Creating file: $filename"
touch "$filename"
Previous

25 Informatica Interview Questions and Answers

Back to Interview
Next

10 React Hook Interview Questions and Answers