Shell Programming & Scripting - Complete Interview Guide
Table of Contents
1. Shell Basics
2. Shell Scripting Fundamentals
3. Variables and Parameters
4. Control Structures
5. Functions
6. File Operations
7. Text Processing
8. Advanced Concepts
9. Interview Questions & Answers
Shell Basics
What is Shell?
Shell is a command-line interpreter that provides an interface between the user and the operating system
kernel. It reads commands from the user and executes them.
Types of Shells
Bash (Bourne Again Shell) - Most commonly used
Sh (Bourne Shell) - Original Unix shell
Csh (C Shell) - C-like syntax
Ksh (Korn Shell) - Enhanced Bourne shell
Zsh (Z Shell) - Extended Bash with additional features
Shell Scripting Fundamentals
Shebang Line
bash
#!/bin/bash
The shebang tells the system which interpreter to use.
Comments
bash
# This is a single line comment
:'
This is a
multi-line comment
'
Basic Script Structure
bash
#!/bin/bash
# Script description
# Author: Your Name
# Date: Date
# Commands go here
echo "Hello World"
Variables and Parameters
Variable Declaration
bash
# Variable assignment (no spaces around =)
name="John"
age=25
readonly PI=3.14159 # Read-only variable
Variable Access
bash
echo $name
echo ${name} # Preferred method
echo "Hello $name"
echo 'Hello $name' # Single quotes prevent expansion
Special Variables
bash
$0 # Script name
$1-$9 # Command line arguments
$# # Number of arguments
$@ # All arguments as separate words
$* # All arguments as single word
$$ # Process ID
$? # Exit status of last command
$! # Process ID of last background command
Environment Variables
bash
export PATH="/usr/local/bin:$PATH"
echo $HOME
echo $USER
echo $PATH
Control Structures
If-Else Statements
bash
#!/bin/bash
if [ condition ]; then
# statements
elif [ condition ]; then
# statements
else
# statements
fi
Comparison Operators
bash
# Numeric comparisons
-eq # equal
-ne # not equal
-lt # less than
-le # less than or equal
-gt # greater than
-ge # greater than or equal
# String comparisons
= # equal
!= # not equal
-z # string is empty
-n # string is not empty
# File tests
-f # file exists and is regular file
-d # directory exists
-r # file is readable
-w # file is writable
-x # file is executable
Loops
For Loop
bash
# Traditional for loop
for i in {1..10}; do
echo $i
done
# Array iteration
fruits=("apple" "banana" "orange")
for fruit in "${fruits[@]}"; do
echo $fruit
done
# C-style for loop
for ((i=1; i<=10; i++)); do
echo $i
done
While Loop
bash
counter=1
while [ $counter -le 10 ]; do
echo $counter
((counter++))
done
Until Loop
bash
counter=1
until [ $counter -gt 10 ]; do
echo $counter
((counter++))
done
Case Statement
bash
case $variable in
pattern1)
# statements
;;
pattern2|pattern3)
# statements
;;
*)
# default case
;;
esac
Functions
Function Definition
bash
# Method 1
function_name() {
# function body
echo "Hello from function"
}
# Method 2
function function_name {
# function body
}
Function with Parameters
bash
greet() {
echo "Hello $1, you are $2 years old"
}
greet "John" 25
Return Values
bash
add_numbers() {
local result=$(($1 + $2))
echo $result
}
result=$(add_numbers 5 3)
echo "Result: $result"
File Operations
Reading Files
bash
# Read line by line
while IFS= read -r line; do
echo "$line"
done < [Link]
# Read entire file
content=$(cat [Link])
Writing to Files
bash
echo "Hello" > [Link] # Overwrite
echo "World" >> [Link] # Append
File Testing
bash
if [ -f "[Link]" ]; then
echo "File exists"
fi
if [ -d "directory" ]; then
echo "Directory exists"
fi
Text Processing
Common Commands
bash
# grep - pattern matching
grep "pattern" [Link]
grep -i "pattern" [Link] # Case insensitive
grep -r "pattern" directory # Recursive
# sed - stream editor
sed 's/old/new/g' [Link] # Replace all occurrences
sed -i 's/old/new/g' [Link] # In-place editing
# awk - pattern scanning and processing
awk '{print $1}' [Link] # Print first column
awk '/pattern/ {print}' [Link] # Print lines matching pattern
# cut - extract columns
cut -d',' -f1 [Link] # First column of CSV
cut -c1-10 [Link] # Characters 1-10
# sort and uniq
sort [Link] | uniq # Sort and remove duplicates
sort -n [Link] # Numeric sort
Advanced Concepts
Arrays
bash
# Declaration
arr=("element1" "element2" "element3")
# Access elements
echo ${arr[0]} # First element
echo ${arr[@]} # All elements
echo ${#arr[@]} # Array length
# Add elements
arr+=("element4")
Command Substitution
bash
current_date=$(date)
file_count=`ls | wc -l`
Process Substitution
bash
diff <(command1) <(command2)
Regular Expressions
bash
# Basic regex patterns
. # Any single character
* # Zero or more of preceding character
^ # Start of line
$ # End of line
[] # Character class
\ # Escape character
Error Handling
bash
# Exit on error
set -e
# Custom error handling
command || { echo "Command failed"; exit 1; }
# Check exit status
if ! command; then
echo "Command failed"
fi
Interview Questions & Answers
Basic Questions
Q1: What is the difference between shell and shell scripting? A: Shell is a command-line interpreter
that provides interface between user and OS kernel. Shell scripting is writing a series of commands in a
file to be executed by the shell interpreter.
Q2: What is the shebang line and why is it important? A: The shebang line (#!/bin/bash) is the first line
in a script that tells the system which interpreter to use for executing the script. It's important because it
ensures the script runs with the correct shell regardless of the user's default shell.
Q3: How do you make a shell script executable? A: Use the chmod command: chmod +x [Link] or
chmod 755 [Link]
Q4: What's the difference between single quotes and double quotes? A:
Single quotes ('') preserve the literal value of all characters
Double quotes ("") allow variable expansion and command substitution
Q5: How do you pass arguments to a shell script? A: Arguments are passed when calling the script:
./[Link] arg1 arg2 . Inside the script, access them using $1, $2, etc.
Variable Questions
Q6: What's the difference between $ and $@?* A:
$* treats all arguments as a single word
$@ treats each argument as a separate word
Use "$@" to preserve argument boundaries
Q7: How do you check if a variable is empty? A:
bash
if [ -z "$variable" ]; then
echo "Variable is empty"
fi
Q8: What are environment variables? A: Environment variables are global variables available to all
processes. Common ones include PATH, HOME, USER, SHELL.
Q9: How do you export a variable? A: export VARIABLE_NAME=value makes the variable available to
child processes.
Q10: What's the difference between local and global variables? A: Local variables are accessible only
within the function where they're defined. Global variables are accessible throughout the script.
Control Structure Questions
Q11: Write a script to check if a number is even or odd. A:
bash
#!/bin/bash
read -p "Enter a number: " num
if [ $((num % 2)) -eq 0 ]; then
echo "$num is even"
else
echo "$num is odd"
fi
Q12: How do you create an infinite loop? A:
bash
while true; do
# commands
done
# Or
while :; do
# commands
done
Q13: What's the difference between break and continue? A:
break: exits the loop completely
continue: skips current iteration and continues with next
Q14: Write a script to print numbers from 1 to 10. A:
bash
#!/bin/bash
for i in {1..10}; do
echo $i
done
Q15: How do you implement a case statement for menu selection? A:
bash
echo "Select option: 1) List files 2) Show date 3) Exit"
read choice
case $choice in
1) ls -l ;;
2) date ;;
3) exit 0 ;;
*) echo "Invalid option" ;;
esac
File Operation Questions
Q16: How do you check if a file exists? A:
bash
if [ -f "filename" ]; then
echo "File exists"
fi
Q17: How do you read a file line by line? A:
bash
while IFS= read -r line; do
echo "$line"
done < [Link]
Q18: How do you append text to a file? A: echo "text" >> [Link]
Q19: What's the difference between > and >>? A:
> overwrites the file
>> appends to the file
Q20: How do you create a directory if it doesn't exist? A:
bash
if [ ! -d "directory_name" ]; then
mkdir directory_name
fi
# Or simply: mkdir -p directory_name
Text Processing Questions
Q21: How do you count the number of lines in a file? A: wc -l [Link]
Q22: How do you find and replace text in a file? A: sed -i 's/old_text/new_text/g' [Link]
Q23: How do you extract the nth column from a file? A: awk '{print $n}' [Link] or cut -f n
[Link]
Q24: How do you sort a file and remove duplicates? A: sort [Link] | uniq
Q25: How do you search for a pattern in multiple files? A: grep -r "pattern" directory/
Function Questions
Q26: How do you define a function in shell? A:
bash
function_name() {
# function body
}
Q27: How do you return a value from a function? A: Use echo or return statement:
bash
get_sum() {
echo $(($1 + $2))
}
result=$(get_sum 5 3)
Q28: What are local variables in functions? A: Variables declared with local keyword are only
accessible within the function.
Q29: How do you call a function with parameters? A: function_name param1 param2
Q30: Can you have nested functions in shell? A: Shell doesn't support true nested functions, but you
can define functions inside other functions that are globally accessible.
Advanced Questions
Q31: What is command substitution? A: Command substitution allows you to use the output of a
command as an argument to another command. Syntax: $(command) or `command`
Q32: What are here documents? A: Here documents allow you to pass multiple lines of input to a
command:
bash
cat << EOF
Line 1
Line 2
EOF
Q33: How do you handle errors in shell scripts? A:
bash
set -e # Exit on any error
command || { echo "Command failed"; exit 1; }
Q34: What is the difference between $? and $!? A:
$? contains the exit status of the last executed command
$! contains the process ID of the last background process
Q35: How do you debug a shell script? A:
Use set -x for execution tracing
Use bash -x [Link]
Add echo statements for debugging
Process Management Questions
Q36: How do you run a command in the background? A: Add & at the end: command &
Q37: How do you bring a background job to foreground? A: Use fg %jobnumber or just fg
Q38: How do you list all running jobs? A: Use jobs command
Q39: How do you kill a process? A:
kill PID (SIGTERM)
kill -9 PID (SIGKILL)
killall process_name
Q40: What's the difference between kill and killall? A:
kill terminates specific process by PID
killall terminates all processes with given name
Input/Output Questions
Q41: How do you read user input in shell script? A:
bash
read -p "Enter your name: " name
echo "Hello $name"
Q42: What are the three types of redirection? A:
Standard input (stdin) - 0
Standard output (stdout) - 1
Standard error (stderr) - 2
Q43: How do you redirect both stdout and stderr to a file? A: command > [Link] 2>&1 or command
&> [Link]
Q44: How do you suppress error messages? A: command 2>/dev/null
Q45: What is pipe (|) operator? A: Pipe operator passes the output of one command as input to
another command.
String Manipulation Questions
Q46: How do you get the length of a string? A: ${#string} or expr length "$string"
Q47: How do you extract substring? A: ${string:start:length} - Example: ${string:0:5} extracts first 5
characters
Q48: How do you replace part of a string? A:
${string/old/new} - Replace first occurrence
${string//old/new} - Replace all occurrences
Q49: How do you convert string to uppercase/lowercase? A:
Uppercase: ${string^^} or echo "$string" | tr '[:lower:]' '[:upper:]'
Lowercase: ${string,,} or echo "$string" | tr '[:upper:]' '[:lower:]'
Q50: How do you check if string contains substring? A:
bash
if [[ "$string" == *"substring"* ]]; then
echo "Contains substring"
fi
Array Questions
Q51: How do you declare an array? A:
bash
arr=("element1" "element2" "element3")
# Or
declare -a arr
arr[0]="element1"
Q52: How do you access array elements? A:
Single element: ${arr[index]}
All elements: ${arr[@]} or ${arr[*]}
Array length: ${#arr[@]}
Q53: How do you add elements to an array? A: arr+=("new_element")
Q54: How do you iterate through an array? A:
bash
for element in "${arr[@]}"; do
echo $element
done
Q55: How do you delete an array element? A: unset arr[index]
File Permission Questions
Q56: How do you change file permissions? A: chmod permissions filename
Numeric: chmod 755 file
Symbolic: chmod u+x file
Q57: What do the numbers in chmod mean? A:
4 = read (r)
2 = write (w)
1 = execute (x)
First digit: owner, Second: group, Third: others
Q58: How do you change file ownership? A: chown user:group filename
Q59: How do you find files with specific permissions? A: find /path -perm 755
Q60: How do you make a script executable for everyone? A: chmod a+x [Link]
Process Questions
Q61: How do you find process ID of a running process? A:
ps aux | grep process_name
pgrep process_name
pidof process_name
Q62: How do you check if a process is running? A:
bash
if pgrep process_name > /dev/null; then
echo "Process is running"
fi
Q63: How do you wait for a background process to complete? A: wait $PID or just wait for all
background processes
Q64: What's the difference between exec and source? A:
exec replaces current shell with new command
source (or .) executes script in current shell environment
Q65: How do you create a daemon process? A:
bash
nohup command &
# Or
command > /dev/null 2>&1 &
Command Line Arguments
Q66: How do you validate command line arguments? A:
bash
if [ $# -ne 2 ]; then
echo "Usage: $0 arg1 arg2"
exit 1
fi
Q67: How do you set default values for parameters? A: ${parameter:-default_value}
Q68: How do you process options in a script? A:
bash
while getopts "h:v:f:" opt; do
case $opt in
h) echo "Help option" ;;
v) verbose=$OPTARG ;;
f) filename=$OPTARG ;;
\?) echo "Invalid option" ;;
esac
done
Q69: How do you shift command line arguments? A: shift removes $1 and shifts all arguments left
Q70: How do you handle unlimited number of arguments? A: Use $@ to access all arguments or loop
through them
System Administration Questions
Q71: How do you check disk usage? A: df -h (disk free) or du -sh directory (disk usage)
Q72: How do you find files larger than specific size? A: find /path -size +100M
Q73: How do you compress and extract files? A:
Compress: tar -czf [Link] directory/
Extract: tar -xzf [Link]
Q74: How do you monitor system resources? A: top , htop , ps aux , free -h , iostat
Q75: How do you schedule a script to run automatically? A: Use cron: crontab -e and add 0 2 * * *
/path/to/[Link]
Network Questions
Q76: How do you check network connectivity? A: ping hostname or curl -I [Link]
Q77: How do you download a file from internet? A: wget URL or curl -O URL
Q78: How do you check open ports? A: netstat -tlnp or ss -tlnp
Q79: How do you find IP address of a domain? A: nslookup [Link] or dig [Link]
Q80: How do you test if a port is open? A: nc -zv hostname port or telnet hostname port
Security Questions
Q81: How do you generate random passwords? A:
bash
openssl rand -base64 12
# Or
tr -dc A-Za-z0-9 </dev/urandom | head -c 12
Q82: How do you hash a password? A: echo -n "password" | sha256sum
Q83: How do you securely delete a file? A: shred -vfz -n 3 filename
Q84: How do you check file integrity? A: md5sum filename or sha256sum filename
Q85: How do you encrypt/decrypt files? A:
Encrypt: gpg -c filename
Decrypt: gpg [Link]
Performance Questions
Q86: How do you measure script execution time? A: time ./[Link]
Q87: How do you run multiple commands in parallel? A:
bash
command1 &
command2 &
wait
Q88: How do you limit script execution time? A: timeout 10s ./[Link]
Q89: How do you optimize shell script performance? A:
Avoid unnecessary loops
Use built-in commands instead of external programs
Use arrays instead of multiple variables
Minimize subprocess creation
Q90: How do you profile a shell script? A: Use set -x for detailed execution trace
Practical Scenario Questions
Q91: Write a script to backup files older than 30 days. A:
bash
#!/bin/bash
find /source -type f -mtime +30 -exec cp {} /backup/ \;
Q92: Write a script to monitor log file for errors. A:
bash
#!/bin/bash
tail -f /var/log/[Link] | grep -i error | while read line; do
echo "ERROR: $line" | mail -s "Error Alert" admin@[Link]
done
Q93: Write a script to clean up temporary files. A:
bash
#!/bin/bash
find /tmp -name "*.tmp" -mtime +7 -delete
find /tmp -type f -empty -delete
Q94: How do you create a script that runs different commands based on OS? A:
bash
#!/bin/bash
case "$(uname -s)" in
Linux*) echo "Linux system" ;;
Darwin*) echo "Mac system" ;;
CYGWIN*) echo "Windows system" ;;
esac
Q95: Write a script to check service status. A:
bash
#!/bin/bash
service_name="apache2"
if systemctl is-active --quiet $service_name; then
echo "$service_name is running"
else
echo "$service_name is not running"
fi
Database Integration Questions
Q96: How do you connect to MySQL from shell script? A:
bash
mysql -u username -p password -e "SELECT * FROM table;" database_name
Q97: How do you execute SQL queries from shell script? A:
bash
mysql -u user -p database << EOF
SELECT * FROM users WHERE age > 25;
EOF
Q98: How do you backup a database using shell script? A:
bash
mysqldump -u username -p password database_name > [Link]
Error Handling Questions
Q99: How do you handle command failures gracefully? A:
bash
if ! command; then
echo "Command failed, attempting recovery..."
# Recovery logic
fi
Q100: How do you create a log file for script execution? A:
bash
#!/bin/bash
LOG_FILE="/var/log/[Link]"
exec > >(tee -a $LOG_FILE)
exec 2>&1
echo "Script started at $(date)"
Q101: How do you validate input parameters? A:
bash
validate_email() {
if [[ $1 =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
return 0
else
return 1
fi
}
Q102: How do you implement retry logic? A:
bash
retry() {
local retries=$1
shift
local command="$@"
for ((i=1; i<=retries; i++)); do
if $command; then
return 0
fi
echo "Attempt $i failed, retrying..."
sleep 2
done
return 1
}
Best Practices
Q103: What are shell scripting best practices? A:
Always use proper shebang
Quote variables to prevent word splitting
Use meaningful variable names
Check command exit status
Handle errors gracefully
Add comments for complex logic
Use functions for reusable code
Validate inputs
Q104: How do you make scripts portable across different Unix systems? A:
Use POSIX-compliant commands
Avoid shell-specific features
Check for command availability before using
Use absolute paths for system commands
Q105: What security considerations should you keep in mind? A:
Validate all inputs
Use full paths for commands
Set appropriate file permissions
Don't hard-code passwords
Sanitize user input
Use quotes around variables
Common Patterns and Snippets
File Processing Template
bash
#!/bin/bash
input_file="$1"
if [ ! -f "$input_file" ]; then
echo "File not found: $input_file"
exit 1
fi
while IFS= read -r line; do
# Process each line
echo "Processing: $line"
done < "$input_file"
Configuration File Parser
bash
#!/bin/bash
config_file="[Link]"
while IFS='=' read -r key value; do
# Skip comments and empty lines
[[ $key =~ ^[[:space:]]*# ]] && continue
[[ -z $key ]] && continue
# Remove leading/trailing whitespace
key=$(echo "$key" | xargs)
value=$(echo "$value" | xargs)
# Store in associative array or variables
declare "$key=$value"
done < "$config_file"
Service Management Script
bash
#!/bin/bash
SERVICE_NAME="myservice"
PID_FILE="/var/run/$SERVICE_NAME.pid"
start_service() {
if [ -f "$PID_FILE" ]; then
echo "Service already running"
return 1
fi
echo "Starting $SERVICE_NAME..."
nohup /path/to/service > /dev/null 2>&1 &
echo $! > "$PID_FILE"
echo "Service started"
}
stop_service() {
if [ ! -f "$PID_FILE" ]; then
echo "Service not running"
return 1
fi
PID=$(cat "$PID_FILE")
kill "$PID"
rm -f "$PID_FILE"
echo "Service stopped"
}
case "$1" in
start) start_service ;;
stop) stop_service ;;
restart) stop_service && start_service ;;
*) echo "Usage: $0 {start|stop|restart}" ;;
esac
This comprehensive guide covers all essential shell scripting concepts and includes 105+ questions with
detailed answers that are commonly asked in technical interviews, especially for companies like NRI
Fintech.