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.
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.
.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/
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"
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
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
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."
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"
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."
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
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.
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"
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
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
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
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.
When writing shell scripts, follow security best practices to prevent vulnerabilities. Here are some key practices:
grep
, sed
, or awk
to filter inputs."$variable"
instead of $variable
.mktemp
, to avoid race conditions and unauthorized access.set -e
to exit the script on any command failure.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"