What is Shell Scripting, and why do interviewers ask about it? This page provides a complete collection of Shell Interview Questions and Answers designed for frontend developers, full-stack developers, React developers, Angular developers, and software engineers preparing for technical interviews.
Shell is a strongly typed programming language developed by Microsoft that extends JavaScript by adding static typing, interfaces, advanced type checking, and modern development features. It helps developers build scalable and maintainable applications.
This interview guide covers beginner, intermediate, and advanced Shell concepts including types, interfaces, classes, generics, decorators, utility types, modules, Shell with React, Angular, Node.js, and real-world coding interview scenarios.
Why companies hire for Shell Scripting Strong static typing – catches errors at compile time, reducing runtime bugs Excellent tooling and IDE support – autocompletion, navigation, and refactoring Superset of JavaScript – works seamlessly with all existing JavaScript libraries Used by major frameworks like React, Angular, and Vue – essential for large-scale apps Enables scalable and maintainable enterprise-grade applications Growing community, continuous improvements, and high demand in the job market All 100 Freshers 12 Intermediate 10 Experienced 18 Coding 60 100 shown
Basic Shell Scripting Interview Questions for Freshers 12 questions Start here if you are a fresher or switching to Shell Scripting. These fundamentals are asked in almost every first-round and campus interview.
1 How interviewers ask it “What is shell scripting, and where would you use it in a real project?”
Beginner Shell Scripting
Quick answer Shell scripting is the process of writing programs in a shell (command-line interpreter) to automate tasks, manage systems, and perform various operations.
Automation : Automate repetitive tasksSystem administration : Manage and configure systemsBatch processing : Process files and dataIntegration : Connect different toolsPortability : Works across Unix-like systems ShellCopy
#!/bin/bash
echo "Hello, World!" 2 How interviewers ask it “How would you declare variables in a production codebase?”
Beginner Shell Scripting
Quick answer Variables in shell are declared using the variable=value syntax. No spaces around the equals sign.
Declaration : name="value"Access : $name or {name}Local variables : local var="value"Environment variables : export VAR="value"Read-only : readonly VAR="value" ShellCopy
#!/bin/bash
x=10
y=3.14
name="Shell"
is_active=true
echo $x
echo $y
echo $name
echo $is_active 3 How interviewers ask it “What are data types, and where would you use them in a real project?”
Beginner Shell Scripting
Quick answer Shell is dynamically typed. Everything is treated as a string, but arithmetic operations can be performed on numeric strings.
Strings : "Hello"Integers : 10Arrays : (1 2 3)Associative arrays : declare -A mapBooleans : true, false ShellCopy
#!/bin/bash
a=10
d=3.14
f="Hello Shell"
g=true
h=false
j=(1 "hello" 3.14)
k=(1 2 3 4 5)
declare -A l
l[name]="Shell"
l[version]=5.0
m=""
echo $a
echo ${k[0]} 4 How interviewers ask it “Suppose you need to define functions in Shell Scripting today — how do you approach it, and what can go wrong?”
Beginner Shell Scripting
Quick answer Functions in shell are defined using the function_name() { commands; } syntax or function function_name { commands; } .
Functions in shell are defined using the function_name() { commands; } syntax or function function_name { commands; }.
Syntax : my_function() { echo "Hello"; }Parameters : $1, $2Return : return valueLocal variables : local var="value"Export : export -f function_name ShellCopy
#!/bin/bash
add () {
echo $(( $1 + $2 ))
}
greet () {
local name="${1:-Guest} "
echo "Hello, $name !"
}
subtract () {
echo $(( $1 - $2 ))
}
sum_all () {
local sum =0
for num in "$@ " ; do
sum =$((sum + num))
done
echo $sum
}
create_person () {
local name="$1 "
local age="${2:-0} "
local city="${3:-Unknown} "
echo "Name: $name , Age: $age , City: $city "
}
add 5 3
greet "Alice"
subtract 10 4
sum_all 1 2 3 4 5
create_person "Alice" 25 "NYC" 5 How interviewers ask it “Let's start with the basics — how would you explain arrays in Shell Scripting?”
Beginner Shell Scripting
Quick answer Arrays in shell are ordered collections that can hold multiple values. They support both indexed and associative arrays.
Indexed arrays : arr=(1 2 3)Associative arrays : declare -A arrAccess : {arr[0]}Add : arr+=(4)Length : {#arr[@]} ShellCopy
#!/bin/bash
arr=(1 2 3 4 5)
doubled=()
for i in "${arr[@]} " ; do
doubled+=($((i * 2 )))
done
echo "${doubled[@]} "
evens=()
for i in "${arr[@]} " ; do
if [ $((i % 2 )) -eq 0 ]; then
evens+=($i )
fi
done
echo "${evens[@]} "
sum =0
for i in "${arr[@]} " ; do
sum =$((sum + i))
done
echo $sum
arr+=(6)
echo "${arr[@]} "
unset 'arr[-1]'
echo "${arr[@]} "
a=(1 2 3)
b=(4 5 6)
c=()
for i in "${!a[@]} " ; do
c+=($((a[i] + b[i])))
done
echo "${c[@]} " 6 How interviewers ask it “In simple words, what are associative arrays? Explain it like you would to a new teammate.”
Beginner Shell Scripting
Quick answer Associative arrays in shell are key-value pairs (dictionaries) declared with declare -A .
Associative arrays in shell are key-value pairs (dictionaries) declared with declare -A.
Declaration : declare -A mapAdd : map[key]="value"Access : {map[key]}Keys : {!map[@]}Check : [[ -v map[key] ]] ShellCopy
#!/bin/bash
declare -A person
person[name]="Alice"
person[age]=25
person[city]="NYC"
echo "${person[name]} "
echo "${person[age]} "
person[country]="USA"
person[age]=26
city="${person[city]:-Unknown} "
echo "${!person[@]} "
echo "${person[@]} "
for key in "${!person[@]} " ; do
echo "$key => ${person[$key]} "
done
unset 'person[country]'
if [[ -v person[name] ]]; then
echo "Name exists"
fi
keys=(1 2 3 4 5)
values=(1 4 9 16 25)
declare -A squares
for i in "${!keys[@]} " ; do
squares[${keys[i]} ]=${values[i]}
done 7 How interviewers ask it “In simple words, what are tuples? Explain it like you would to a new teammate.”
Beginner Shell Scripting
Quick answer Shell doesn't have native tuples, but arrays can be used as tuple-like structures for ordered collections.
Arrays as tuples : (1 "hello" 3.14)Access : {tuple[0]}Unpacking : read a b c <<< "$tuple"Return multiple values : Use echo with readConcatenation : t3=("{t1[@]}" "{t2[@]}") ShellCopy
#!/bin/bash
t=(1 "hello" 3.14 true )
echo "${t[0]} "
echo "${t[1]} "
tuple=(10 20 30)
a=${tuple[0]}
b=${tuple[1]}
c=${tuple[2]}
echo "$a , $b , $c "
divide () {
local a=$1
local b=$2
echo $((a / b))
echo $((a % b))
}
read quotient remainder < <(divide 10 3)
echo "Quotient: $quotient , Remainder: $remainder "
t1=(1 2 3)
t2=(4 5 6)
t3=("${t1[@]} " "${t2[@]} " )
echo "${t3[@]} " 8 How interviewers ask it “In simple words, what are control flow statements? Explain it like you would to a new teammate.”
Beginner Shell Scripting
Quick answer Shell provides standard control flow statements including conditionals, loops, and case statements.
If-else : if [ condition ]; then ... fiFor loop : for i in {1..10}; do ... doneWhile loop : while [ condition ]; do ... doneCase : case $var in pattern) ...;; esacBreak/Continue : break, continue ShellCopy
#!/bin/bash
age=25
if [ $age -lt 18 ]; then
echo "Minor"
elif [ $age -lt 65 ]; then
echo "Adult"
else
echo "Senior"
fi
[ $age -ge 18 ] && status="Adult" || status="Minor"
echo $status
for i in {1..5}; do
echo $i
done
fruits=("apple" "banana" "orange" )
for fruit in "${fruits[@]} " ; do
echo $fruit
done
i=1
while [ $i -le 5 ]; do
echo $i
i=$((i + 1 ))
done
for i in {1..10}; do
if [ $i -eq 6 ]; then
break
fi
if [ $((i % 2 )) -eq 0 ]; then
continue
fi
echo $i
done 9 How interviewers ask it “How would you generate arrays in a production codebase?”
Beginner Shell Scripting
Quick answer Arrays in shell can be generated using loops, brace expansion, seq , and various built-in mechanisms.
Arrays in shell can be generated using loops, brace expansion, seq, and various built-in mechanisms.
Brace expansion : {1..10}Seq : $(seq 1 10)Loops : for i in {1..10}; do arr+=($i); doneMap : Transform with loopsFilter : Conditional addition ShellCopy
#!/bin/bash
squares=()
for i in {1..10}; do
squares+=($((i * i)))
done
echo "${squares[@]} "
evens=()
for i in {1..20}; do
if [ $((i % 2 )) -eq 0 ]; then
evens+=($i )
fi
done
echo "${evens[@]} "
pairs=()
for i in {1..3}; do
for j in {1..3}; do
pairs+=("$i ,$j " )
done
done
echo "${pairs[@]} "
results=()
for i in {1..10}; do
if [ $((i % 2 )) -eq 0 ]; then
results+=("even" )
else
results+=("odd" )
fi
done
echo "${results[@]} "
for i in $(seq 1 10); do
echo $i
done 10 How interviewers ask it “How would you work with strings in a production codebase?”
Beginner Shell Scripting
Quick answer Shell provides various string manipulation operations including concatenation, substitution, and extraction.
Concatenation : "$str1 $str2"Length : {#string}Substring : {string:0:5}Replace : {string/old/new}Case conversion : {string^^}, {string,,} ShellCopy
#!/bin/bash
str1="Hello"
str2='World'
str3="Multi-line
string"
greeting="$str1 $str2 "
echo "$greeting "
name="Shell"
version=5.0
echo "Welcome to $name version $version "
text="Hello, World!"
echo "${#text} "
echo "${text^^} "
echo "${text,,} "
echo "${text/World/Shell} "
echo "${text:0:5} "
IFS=' ' read -ra words <<< "Hello World Shell"
echo "${words[@]} "
joined=$(IFS='-' ; echo "${words[*]} " )
echo "$joined "
[ "hello" == "hello" ] && echo "Equal"
[ "hello" < "world" ] && echo "Less than"
printf "Value: %.2f
" 3.1415911 How interviewers ask it “What are modules, and where would you use them in a real project?”
Beginner Shell Scripting
Quick answer Shell modules are scripts that can be sourced (included) to reuse functions and variables across scripts.
Sourcing : source script.sh or . script.shFunctions : Define reusable functionsVariables : Define constantsExport : export -f function_nameLibraries : Organize code into files ShellCopy
#!/bin/bash
my_function () {
local local_var="Local"
global_var="Global"
}
export -f my_function
12 How interviewers ask it “In simple words, what are variables and types? Explain it like you would to a new teammate.”
Beginner Shell Scripting
Quick answer Shell variables are dynamically typed. The declare builtin can be used to set variable attributes.
Local : local var="value"Global : var="value"Environment : export var="value"Read-only : readonly var="value"Special variables : $0, $@, $# ShellCopy
#!/bin/bash
name="Alice"
age=25
city="NYC"
my_function () {
local local_var="Local"
global_var="Global"
}
export ENV_VAR="Environment"
readonly CONSTANT=100
echo "Script name: $0 "
echo "First argument: $1 "
echo "All arguments: $@ "
echo "Number of arguments: $# "
echo "Exit code of last command: $?"
echo "Process ID: $$"
declare -i integer =42
declare -r readonly_var=100
declare -a array=(1 2 3)
declare -A associative=([key]="value" )
if [ -z "${var+x} " ]; then
echo "var is unset"
fi
name="${name:-Default} "
var=name
echo ${!var}
Advanced Shell Scripting Interview Questions for Experienced Developers 18 questions Senior-level Shell Scripting questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.
23 How interviewers ask it “Suppose you need to do parallel computing in Shell Scripting today — how do you approach it, and what can go wrong?”
Advanced Shell Scripting
Quick answer Shell supports parallel computing through background processes, xargs , GNU parallel, and job control.
Shell supports parallel computing through background processes, xargs, GNU parallel, and job control.
Background : command &wait : wait $pidxargs : xargs -P4GNU parallel : parallel -j4Subshells : ( command ) & ShellCopy
#!/bin/bash
parallel_task () {
sleep 2
echo "Task completed"
}
parallel_task &
parallel_task &
wait
echo "All tasks completed"
echo {1..10} | xargs -n1 -P4 -I{} echo "Processing {}"
(
sleep 2
echo "Task 1 done"
) &
(
sleep 1
echo "Task 2 done"
) &
wait
for i in {1..10}; do
(
sleep 1
echo "Processing $i "
) &
done
wait
while read -r line; do
(
echo "Processing $line "
) &
done < input.txt
wait
mkfifo pipe
(
echo "Data" > pipe
) &
read data < pipe
rm pipe
find . -name "*.txt" -print0 | xargs -0 -P4 -I{} echo "Processing {}" 24 How interviewers ask it “Walk me through metaprogramming in Shell Scripting — how it works and where you've used it.”
Advanced Shell Scripting
Quick answer Shell supports metaprogramming through eval , dynamic variable names, and code generation.
Shell supports metaprogramming through eval, dynamic variable names, and code generation.
eval : eval "echo Hello"Dynamic variables : {!var_name}Dynamic functions : eval "func() { echo Hi; }"Code generation : Using here-documentsSource : source generated.sh ShellCopy
#!/bin/bash
code='echo "Hello World"'
eval "$code "
function add () {
echo $(( $1 + $2 ))
}
func_name="add"
$func_name 5 3
var_name="x"
eval "$var_name =10"
echo $x
var="name"
name="Alice"
echo "${!var} "
eval 'my_function() { echo "Dynamic function"; }'
my_function
cat << 'EOF' > generated.sh
echo "Generated script"
EOF
chmod +x generated.sh
./generated.sh
source ./config.sh
declare -a dynamic_array
for i in {1..5}; do
dynamic_array+=("$i " )
done
alias my_cmd='echo "Hello"'
my_cmd
trap 'echo "Interrupted"' INT
a="Hello"
b="a"
echo "${!b} " 25 How interviewers ask it “Suppose you need to interface with C today — how do you approach it, and what can go wrong?”
Advanced Shell Scripting
Quick answer Shell can interface with C programs by compiling and running them, or by using system calls.
Compile : gcc -o program program.cRun : ./programPass arguments : ./program arg1 arg2Check exit code : $?Environment : export VAR="value" ShellCopy
#!/bin/bash
./program
./program arg1 arg2
./program | while read -r line; do
echo "$line "
done
./program | grep "pattern"
./program
if [ $? -eq 0 ]; then
echo "Success"
else
echo "Failed"
fi
export MY_VAR="value"
./program
./program input.txt output.txt
gcc -o program program.c && ./program
./program &
kill -SIGUSR1 $!26 How interviewers ask it “How would you optimize performance in a production codebase?”
Advanced Shell Scripting
Quick answer Shell performance can be optimized through built-in commands, avoiding subshells, and using efficient loops.
Built-ins : Use shell built-ins vs externalAvoid subshells : Use pushd vs (cd ...)Arrays : Use arrays for collectionsProcess substitution : <(command)Brace expansion : {1..1000} ShellCopy
#!/bin/bash
files=()
for file in *; do
files+=("$file " )
done
while read -r line; do
echo "$line "
done < <(find . -name "*.txt" )
for i in {1..1000}; do
echo $i
done
sum =0
for i in {1..1000}; do
((sum += i))
done
shopt -s nullglob
for file in *.txt; do
echo "$file "
done
while IFS= read -r line; do
echo "$line "
done < file.txt
exec > output.log 2>&1
ulimit -n 4096
time ./script.sh
set -o pipefail
compgen -c | head -10
shopt -s extglob27 How interviewers ask it “How would you do networking in a production codebase?”
Advanced Shell Scripting
Quick answer Shell provides networking through curl , wget , nc , and other network tools.
Shell provides networking through curl, wget, nc, and other network tools.
curl : curl -s URLwget : wget -qO- URLnetcat : nc -zv host portSSH : ssh user@host commandSCP : scp local.txt user@host:/remote/ ShellCopy
#!/bin/bash
fetch_data () {
curl -s "$1 "
}
post_data () {
curl -s -X POST -H "Content-Type: application/json" -d "$2 " "$1 "
}
wget -O output.html https://example.com
nc -zv example.com 80
if [ $? -eq 0 ]; then
echo "Port 80 is open"
fi
send_tcp () {
local host=$1
local port=$2
local message=$3
echo "$message " | nc "$host " "$port "
}
host example.com
nslookup example.com
dig example.com
ping -c 4 example.com
traceroute example.com
28 How interviewers ask it “How would you work with JSON in a production codebase?”
Advanced Shell Scripting
Quick answer Shell works with JSON using jq for parsing, manipulation, and generation of JSON data.
Parse : echo '{"name":"Alice"}' | jq '.name'Pretty print : echo '{"name":"Alice"}' | jq '.'Generate : jq -n '{name: "Bob"}'Arrays : echo '[1,2,3]' | jq '.[]'Nested : echo '{"user":{"name":"Alice"}}' | jq '.user.name' ShellCopy
#!/bin/bash
data='{"name":"Alice","age":25,"city":"NYC","hobbies":["reading","coding"]}'
echo "$data " | jq '.name'
echo "$data " | jq '.age'
echo "$data " | jq '.hobbies[0]'
echo "$data " | jq '.'
jq -n '{name: "Bob", age: 30, city: "LA"}'
echo '[1,2,3,4,5]' | jq '.'
nested='{"user":{"id":1,"profile":{"name":"Alice","email":"alice@example.com"}}}'
echo "$nested " | jq '.user.profile.name'
echo '{"name":"Alice","age":25}' | jq '.' > output.json
name="Bob"
age=30
echo "{}" | jq --arg n "$name " --arg a "$age " '.name=$n | .age=$a'
echo '["apple","banana","orange"]' | jq '.[]'
echo '{"name":"Alice","age":25}' | jq '{fullname: .name, years: .age}'
if echo "$data " | jq empty 2>/dev/null; then
echo "Valid JSON"
else
echo "Invalid JSON"
fi 29 How interviewers ask it “How would you test code in a production codebase?”
Advanced Shell Scripting
Quick answer Shell testing can be done with custom assert functions, BATS (Bash Automated Testing System), or shunit2.
Custom asserts : assert() { [ "$1" = "$2" ]; }BATS : @test "name" { [ ... ]; }shunit2 : test_addition() { assertEquals ...; }Test suites : Group testsCoverage : bashcov ShellCopy
#!/bin/bash
assert () {
if [ "$1 " = "$2 " ]; then
echo "PASS: $3 "
return 0
else
echo "FAIL: $3 - Expected: $1 , Got: $2 "
return 1
fi
}
test_addition () {
result=$(add 2 2)
assert 4 "$result " "2 + 2 = 4"
}
test_float () {
local result=$(echo "0.1 + 0.2" | bc)
local expected="0.3"
if (( $(echo "$result == $expected " | bc -l) )); then
echo "PASS: Float test"
else
echo "FAIL: Float test - Expected: $expected , Got: $result "
fi
}
test_exit_code () {
./script.sh
if [ $? -eq 0 ]; then
echo "PASS: Exit code test"
else
echo "FAIL: Exit code test - Expected: 0, Got: $?"
fi
}
run_tests () {
test_addition
test_float
test_exit_code
}
30 How interviewers ask it “How would you debug in a production codebase?”
Advanced Shell Scripting
Quick answer Shell provides debugging through trace mode ( set -x ), verbose mode, and various debugging tools.
Shell provides debugging through trace mode (set -x), verbose mode, and various debugging tools.
set -x : Trace executionset -v : Verbose modeecho : Print debug messagestrap : Error handlingshellcheck : Static analysis ShellCopy
#!/bin/bash
debug_function () {
echo "Entering function with x=$1 " >&2
result=$(( $1 * 2 ))
echo "Result = $result " >&2
echo $result
}
debug_function 5
set -x
set +x
set -v
set +v
export PS4='+ $BASH_SOURCE:$LINENO: '
set -x
trap 'echo "Error on line $LINENO"' ERR
logger "Debug message"
logger -t myscript "Debug message with tag"
echo "Hello" | tee -a debug.log
exec 2> debug.log
set -e
set -u
set -o pipefail
trap 'echo "Line $LINENO: $BASH_COMMAND"' DEBUG31 How interviewers ask it “How would you explain abstract types to a junior developer? What are the gotchas?”
Advanced Shell Scripting
Quick answer Shell doesn't have formal abstract types, but functions and case statements can simulate abstract behaviors.
Functions : Define interfacesCase statements : Polymorphic dispatchArrays : Store behaviorsType checking : declare -fInheritance : Function composition ShellCopy
#!/bin/bash
animal () {
local action=$1
shift
case $action in
make_sound) echo "Animal sound" ;;
*) echo "Unknown action" ;;
esac
}
dog () {
local action=$1
shift
case $action in
make_sound) echo "Woof!" ;;
*) animal "$action " "$@ " ;;
esac
}
cat () {
local action=$1
shift
case $action in
make_sound) echo "Meow!" ;;
*) animal "$action " "$@ " ;;
esac
}
sound_maker () {
make_sound "$@ "
}
dog make_sound
cat make_sound
is_animal () {
declare -f "$1 " > /dev/null
}
sparrow () {
local action=$1
shift
case $action in
make_sound) echo "Chirp!" ;;
*) animal "$action " "$@ " ;;
esac
}
if is_animal dog; then
echo "Dog is an animal"
fi
animals=(dog cat sparrow)
for animal in "${animals[@]} " ; do
$animal make_sound
done 32 How interviewers ask it “Our team relies on generic types in Shell Scripting. What should every engineer here know about them?”
Advanced Shell Scripting
Quick answer Shell doesn't have formal generic types, but generic-like behavior can be simulated with arrays and functions.
Generic collections : Use arraysGeneric functions : Accept arrays as argumentsMap : Apply function to each elementFilter : Select by predicateReduce : Aggregate values ShellCopy
#!/bin/bash
declare -a list
list_add () {
local -n arr=$1
arr+=("$2 " )
}
list_get () {
local -n arr=$1
echo "${arr[$2]} "
}
list_length () {
local -n arr=$1
echo "${#arr[@]} "
}
map () {
local -n arr=$1
local func=$2
local result=()
for item in "${arr[@]} " ; do
result+=($($func "$item " ))
done
echo "${result[@]} "
}
filter () {
local -n arr=$1
local pred=$2
local result=()
for item in "${arr[@]} " ; do
if $pred "$item " ; then
result+=("$item " )
fi
done
echo "${result[@]} "
}
reduce () {
local -n arr=$1
local func=$2
local acc=$3
for item in "${arr[@]} " ; do
acc=$($func "$acc " "$item " )
done
echo "$acc "
}
numbers=(1 2 3 4 5)
list_add numbers 6
list_get numbers 0
list_length numbers
double () { echo $(( $1 * 2 )); }
is_even () { [ $(( $1 % 2 )) -eq 0 ]; }
doubled=$(map numbers double)
evens=$(filter numbers is_even)
sum =$(reduce numbers add 0)33 How interviewers ask it “Tell me about traits. When are they the right tool, and when would you avoid them?”
Advanced Shell Scripting
Quick answer Traits in shell can be simulated using functions and composition patterns.
Functions as traits : Define reusable behaviorsComposition : Combine multiple traitsMixins : Add behavior to objectsMethod override : Redefine functionsValidation : Trait with validation ShellCopy
#!/bin/bash
Logger () {
log () {
echo "[LOG] $1 "
}
error () {
echo "[ERROR] $1 " >&2
}
}
User () {
local name=""
local age=0
set_name () { name=$1 ; }
get_name () { echo "$name " ; }
set_age () { age=$1 ; }
get_age () { echo "$age " ; }
}
UserWithLogger () {
User
Logger
get_info () {
echo "Name: $(get_name) , Age: $(get_age) "
}
}
user_with_logger=UserWithLogger
$user_with_logger set_name "Alice"
$user_with_logger set_age 25
$user_with_logger get_info
$user_with_logger log "User created"
mixins=()
add_mixin () {
mixins+=("$1 " )
}
apply_mixins () {
for mixin in "${mixins[@]} " ; do
$mixin
done
}
Validator () {
validate_name () {
[[ -n $1 ]] && return 0 || return 1
}
validate_age () {
[[ $1 -gt 0 ]] && return 0 || return 1
}
}
UserWithValidation () {
User
Validator
set_name () {
if validate_name "$1 " ; then
name=$1
else
echo "Invalid name" >&2
fi
}
}34 How interviewers ask it “Our team relies on generators in Shell Scripting. What should every engineer here know about them?”
Advanced Shell Scripting
Quick answer Generators in shell can be implemented using functions with state, or using FIFOs and process substitution.
Stateful functions : Track state in variablesFIFOs : Named pipes for streamingProcess substitution : <(command)Background jobs : Coroutine-like behaviorLazy evaluation : Using temporary files ShellCopy
#!/bin/bash
counter_generator () {
local count=0
next () {
echo $((++count))
}
}
counter=counter_generator
$counter next
$counter next
$counter next
fibonacci_generator () {
local a=0
local b=1
next () {
local c=$a
a=$b
b=$((c + b))
echo $c
}
}
fib=fibonacci_generator
for i in {1..10}; do
$fib next
done
coroutine () {
local pipe="/tmp/coro_$$"
mkfifo "$pipe "
(
echo "Coroutine started"
sleep 2
echo "Coroutine finished"
) > "$pipe " &
cat "$pipe "
rm "$pipe "
}
coproc my_coro {
while read -r cmd; do
case $cmd in
start) echo "Starting" ;;
stop) echo "Stopping" ; break ;;
*) echo "Unknown: $cmd " ;;
esac
done
}
lazy_eval () {
local tmp=$(mktemp )
(
echo "Computing..."
sleep 2
echo "42" > "$tmp "
) &
cat "$tmp "
rm "$tmp "
}
job () {
local name=$1
for i in {1..5}; do
echo "$name : $i "
sleep 1
done
}
job "A" &
job "B" &
wait 35 How interviewers ask it “Tell me about advanced array operations. When are they the right tool, and when would you avoid them?”
Advanced Shell Scripting
Quick answer Shell provides basic array operations, and advanced operations can be implemented using loops and custom functions.
Matrix ops : Nested arraysElement-wise : LoopsTranspose : Swap indicesMultiplication : Dot productsNorm/Trace : Sum calculations ShellCopy
#!/bin/bash
declare -A matrix
for ((i=0 ; i<3 ; i++)); do
for ((j=0 ; j<3 ; j++)); do
matrix[$i ,$j ]=$((i*3 +j+1 ))
done
done
flatten () {
local -n arr=$1
for key in "${!arr[@]} " ; do
echo "${arr[$key]} "
done
}
transpose () {
local -n A=$1
local -n B=$2
for ((i=0 ; i<3 ; i++)); do
for ((j=0 ; j<3 ; j++)); do
B[$j ,$i ]=${A[$i,$j]}
done
done
}
declare -A A
declare -A B
declare -A C
for ((i=0 ; i<3 ; i++)); do
for ((j=0 ; j<3 ; j++)); do
A[$i ,$j ]=$((i*3 +j+1 ))
B[$i ,$j ]=$((A[$i ,$j ] + 1 ))
C[$i ,$j ]=$((A[$i ,$j ] * 2 ))
done
done
mat_mul () {
local -n A=$1
local -n B=$2
local -n R=$3
for ((i=0 ; i<3 ; i++)); do
for ((j=0 ; j<3 ; j++)); do
sum =0
for ((k=0 ; k<3 ; k++)); do
sum =$((sum + A[$i ,$k ] * B[$k ,$j ]))
done
R[$i ,$j ]=$sum
done
done
}
elementwise_mul () {
local -n A=$1
local -n B=$2
local -n R=$3
for ((i=0 ; i<3 ; i++)); do
for ((j=0 ; j<3 ; j++)); do
R[$i ,$j ]=$((A[$i ,$j ] * B[$i ,$j ]))
done
done
}
norm () {
local -n A=$1
local sum =0
for ((i=0 ; i<3 ; i++)); do
for ((j=0 ; j<3 ; j++)); do
sum =$((sum + A[$i ,$j ] * A[$i ,$j ]))
done
done
echo "scale=2; sqrt($sum )" | bc
}
trace () {
local -n A=$1
local sum =0
for ((i=0 ; i<3 ; i++)); do
sum =$((sum + A[$i ,$i ]))
done
echo $sum
}
diag () {
local -n A=$1
for ((i=0 ; i<3 ; i++)); do
echo "${A[$i,$i]} "
done
}36 How interviewers ask it “Suppose you need to handle missing data in Shell Scripting today — how do you approach it, and what can go wrong?”
Advanced Shell Scripting
Quick answer Shell handles missing data using empty strings, {var:-default} , and existence checks.
Shell handles missing data using empty strings, {var:-default}, and existence checks.
Empty strings : Represent nullDefault values : {var:-default}Existence check : [[ -v var ]]Remove : Filter out emptiesReplace : {var:-default} ShellCopy
#!/bin/bash
data=("1" "2" "" "4" "5" "" "7" )
has_missing () {
for item in "${@} " ; do
if [ -z "$item " ]; then
return 0
fi
done
return 1
}
remove_missing () {
local result=()
for item in "${@} " ; do
if [ -n "$item " ]; then
result+=("$item " )
fi
done
echo "${result[@]} "
}
replace_missing () {
local default=$1
shift
local result=()
for item in "${@} " ; do
if [ -n "$item " ]; then
result+=("$item " )
else
result+=("$default " )
fi
done
echo "${result[@]} "
}
x=("1" "2" "" "4" )
y=("5" "6" "" "8" )
z=()
for i in "${!x[@]} " ; do
if [ -n "${x[$i]} " ] && [ -n "${y[$i]} " ]; then
z+=($((x[i] + y[i])))
else
z+=("" )
fi
done
sum_complete=0
for item in "${x[@]} " ; do
if [ -n "$item " ]; then
sum_complete=$((sum_complete + item))
fi
done
value="${data[10]:-default} "
if [ -z "${var+x} " ]; then
echo "var is unset"
fi
var=${var:-default}
name="${name:-Default} " 37 How interviewers ask it “Suppose you need to do sorting and searching in Shell Scripting today — how do you approach it, and what can go wrong?”
Advanced Shell Scripting
Quick answer Shell provides sorting through sort and searching through grep , awk , and loops.
Shell provides sorting through sort and searching through grep, awk, and loops.
sort : sort -nCustom sort : sort -k2Search : grep patternBinary search : Custom implementationContains : [[ $item =~ pattern ]] ShellCopy
#!/bin/bash
arr=(5 2 8 1 9 3)
sorted=($(printf '%s
' "${arr[@]} " | sort -n))
echo "${sorted[@]} "
arr2=("5 apple" "3 banana" "8 cherry" )
sorted2=($(printf '%s
' "${arr2[@]} " | sort -n))
echo "${sorted2[@]} "
arr3=(5 2 8 1 9 3)
sorted3=($(printf '%s
' "${arr3[@]} " | sort -nr))
echo "${sorted3[@]} "
arr4=(1 3 5 7 9 11)
greater_than_5=()
for item in "${arr4[@]} " ; do
if [ $item -gt 5 ]; then
greater_than_5+=("$item " )
fi
done
echo "${greater_than_5[@]} "
first_greater=()
for item in "${arr4[@]} " ; do
if [ $item -gt 5 ]; then
first_greater="$item "
break
fi
done
echo "$first_greater "
last_greater=()
for item in "${arr4[@]} " ; do
if [ $item -gt 5 ]; then
last_greater="$item "
fi
done
echo "$last_greater "
has_seven=0
has_four=0
for item in "${arr4[@]} " ; do
if [ $item -eq 7 ]; then
has_seven=1
fi
if [ $item -eq 4 ]; then
has_four=1
fi
done
echo "Has 7: $has_seven , Has 4: $has_four "
binary_search () {
local arr=("$@ " )
local target=${arr[-1]}
unset 'arr[-1]'
local left=0
local right=$((${#arr[@]} - 1 ))
while [ $left -le $right ]; do
local mid=$(((left + right) / 2 ))
if [ ${arr[$mid]} -eq $target ]; then
echo $mid
return
elif [ ${arr[$mid]} -lt $target ]; then
left=$((mid + 1 ))
else
right=$((mid - 1 ))
fi
done
echo -1
}
arr5=(1 2 3 4 5 6 7)
index=$(binary_search "${arr5[@]} " 5)
echo "Found at index: $index " 38 How interviewers ask it “Our team relies on mathematical operations in Shell Scripting. What should every engineer here know about them?”
Advanced Shell Scripting
Quick answer Shell provides arithmetic operations through $((...)) , bc , and awk .
Shell provides arithmetic operations through $((...)), bc, and awk.
Arithmetic : $((1+2))bc : echo "scale=2; 10/3" | bcTrigonometric : bc -lRandom : $RANDOMStatistics : Custom functions ShellCopy
#!/bin/bash
x=10
y=3
echo "$((x + y) )"
echo "$((x - y) )"
echo "$((x * y) )"
echo "$((x / y) )"
echo "$((x % y) )"
echo "$((x ** y) )"
echo "scale=4; s(3.14159/4)" | bc -l
echo "scale=4; c(3.14159/4)" | bc -l
echo "scale=4; e(1)" | bc -l
echo "scale=4; l(e(1))" | bc -l
echo "scale=4; sqrt(9)" | bc -l
echo "abs(-5) = ${abs#-} "
ceil () {
echo "$1 " | awk '{print ($0 == int($0)) ? $0 : int($0) + 1}'
}
floor () {
echo "$1 " | awk '{print ($0 == int($0)) ? $0 : int($0) - 1}'
}
round () {
echo "$1 " | awk '{print int($1 + 0.5)}'
}
echo $((RANDOM % 10 + 1 ))
echo $((RANDOM % 100 ))
data=(1 2 3 4 5 6 7 8 9 10)
sum =0
for i in "${data[@]} " ; do
sum =$((sum + i))
done
echo "sum = $sum "
echo "mean = $(echo "scale=2; $sum / ${#data[@]} " | bc) "
min=${data[0]}
max=${data[0]}
for i in "${data[@]} " ; do
[ $i -lt $min ] && min=$i
[ $i -gt $max ] && max=$i
done
echo "min = $min , max = $max " 39 How interviewers ask it “How would you do data serialization in a production codebase?”
Advanced Shell Scripting
Quick answer Shell serializes data using text formats like CSV, JSON, YAML, or custom formats with base64 encoding.
CSV : Comma-separated valuesJSON : Using jqYAML : Using yqbase64 : echo "data" | base64Custom : Key-value pairs ShellCopy
#!/bin/bash
data="name:Alice,age:25,city:NYC"
echo "$data " > data.txt
deserialized=$(cat data.txt)
echo "$deserialized "
echo '{"name":"Alice","age":25}' > data.json
cat data.json | jq '.'
echo "name,age,city" > data.csv
echo "Alice,25,NYC" >> data.csv
echo "Bob,30,LA" >> data.csv
encoded=$(echo "Hello World" | base64 )
decoded=$(echo "$encoded " | base64 -d)
tar -czf archive.tar.gz file1 file2
gzip -c data.txt > data.txt.gz
gunzip -c data.txt.gz > data.txt
serialize () {
echo "$1 " | base64
}
deserialize () {
echo "$1 " | base64 -d
}
declare -A person
person[name]="Alice"
person[age]=25
person[city]="NYC"
for key in "${!person[@]} " ; do
echo "$key =${person[$key]} "
done > person.dat
while IFS='=' read -r key value; do
person2["$key " ]="$value "
done < person.dat40 How interviewers ask it “Suppose you need to interface with external systems in Shell Scripting today — how do you approach it, and what can go wrong?”
Advanced Shell Scripting
Quick answer Shell interfaces with external systems through database clients, HTTP tools, SSH, and system commands.
Database : sqlite3, mysqlHTTP : curl, wgetSSH : ssh user@hostSystem : commandEnvironment : export ShellCopy
#!/bin/bash
sqlite3 database.db "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
sqlite3 database.db "INSERT INTO users (name) VALUES ('Alice')"
sqlite3 database.db "SELECT * FROM users"
curl -X GET https://api.github.com
curl -X POST -H "Content-Type: application/json" -d '{"name":"Alice"}' https://httpbin.org/post
system () {
command "$@ "
}
output=$(ls -la)
echo "$output "
export MY_VAR="value"
echo $MY_VAR
temp_file=$(mktemp )
echo "data" > "$temp_file "
rm "$temp_file "
mkfifo pipe
echo "Hello" > pipe &
cat pipe
rm pipe
Shell Scripting Coding Interview Questions (Programs with Code) 60 questions Hands-on Shell Scripting programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.
41 How interviewers ask it “Live coding: Reverse a string in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Reverse a string by iterating from the end to the beginning.
Method : for ((i=${#s}-1; i>=0; i--)); do reversed="${reversed}${s:$i:1}"; doneAlternative : rev commandTime : O(n)Edge cases : Empty string ShellCopy
#!/bin/bash
reverse_string () {
local s="$1 "
local reversed=""
for ((i=${#s} -1 ; i>=0 ; i--)); do
reversed="${reversed} ${s:$i:1} "
done
echo "$reversed "
}
reverse_string_manual () {
local s="$1 "
local len=${#s}
local reversed=""
for ((i=0 ; i<len; i++)); do
reversed="${s:$i:1} $reversed "
done
echo "$reversed "
}
s="hello"
echo "Original: $s "
echo "Reversed: $(reverse_string "$s " ) "
echo "Reversed (manual): $(reverse_string_manual "$s " ) " 42 How interviewers ask it “Live coding: Check palindrome in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Check if a string is a palindrome by comparing it with its reverse.
Method : s == $(reverse_string "$s")Case insensitive : {s,,}Ignore spaces : {s// /}Recursive : Compare ends ShellCopy
#!/bin/bash
is_palindrome () {
local s="${1,,} "
local cleaned="${s// /} "
local reversed=$(reverse_string "$cleaned " )
[ "$cleaned " = "$reversed " ]
}
is_palindrome_manual () {
local s="${1,,} "
local cleaned="${s// /} "
local len=${#cleaned}
for ((i=0 ; i<len/2 ; i++)); do
if [ "${cleaned:$i:1} " != "${cleaned:$len-$i-1:1} " ]; then
return 1
fi
done
return 0
}
strings=("racecar" "hello" "A man a plan a canal Panama" "race a car" )
for s in "${strings[@]} " ; do
if is_palindrome "$s " ; then
echo "" $s " is palindrome"
else
echo "" $s " is not palindrome"
fi
done 43 How interviewers ask it “Can you find max in array in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Find the maximum value by iterating through the array.
Method : max={arr[0]}; for val in "{arr[@]}"; do [ $val -gt $max ] && max=$val; doneAlternative : printf '%s\n' "{arr[@]}" | sort -n | tail -1Empty : Handle empty caseTime : O(n) ShellCopy
#!/bin/bash
find_max () {
local max=$1
shift
for val in "$@ " ; do
if [ $val -gt $max ]; then
max=$val
fi
done
echo $max
}
find_max_manual () {
local arr=("$@ " )
local max=${arr[0]}
for ((i=1 ; i<${#arr[@]} ; i++)); do
if [ ${arr[$i]} -gt $max ]; then
max=${arr[$i]}
fi
done
echo $max
}
arr=(1 5 3 9 2)
echo "Array: ${arr[@]} "
echo "Max: $(find_max "${arr[@]} " ) "
echo "Max (manual): $(find_max_manual "${arr[@]} " ) " 44 How interviewers ask it “Live coding: Remove duplicates in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Remove duplicates by tracking seen items and skipping duplicates.
Method : printf '%s\n' "{arr[@]}" | sort -uManual : seen=(); for item in "{arr[@]}"; do ...Preserve order : Manual methodTime : O(n²) or O(n log n) with sort ShellCopy
#!/bin/bash
remove_duplicates () {
local result=()
local seen=()
for item in "$@ " ; do
local found=0
for seen_item in "${seen[@]} " ; do
if [ "$seen_item " = "$item " ]; then
found=1
break
fi
done
if [ $found -eq 0 ]; then
seen+=("$item " )
result+=("$item " )
fi
done
echo "${result[@]} "
}
remove_duplicates_sort () {
printf '%s
' "$@ " | sort -u
}
arr=("apple" "banana" "apple" "orange" "banana" "grape" )
echo "Original: ${arr[@]} "
echo "Without duplicates: $(remove_duplicates "${arr[@]} " ) "
echo "Without duplicates (sort): $(remove_duplicates_sort "${arr[@]} " ) " 45 How interviewers ask it “Quick coding-round task — merge arrays in Shell Scripting. How would you handle the edge cases?”
Coding Shell Scripting
Quick answer Merge arrays by concatenating or merging sorted arrays.
Concat : result=("{arr1[@]}" "{arr2[@]}")Sorted merge : Compare and addUnique : printf '%s\n' "{arr1[@]}" "{arr2[@]}" | sort -uTime : O(n+m) ShellCopy
#!/bin/bash
merge_arrays () {
echo "${@} "
}
merge_sorted () {
local arr1=("${!1} " )
local arr2=("${!2} " )
local result=()
local i=0 j=0
while [ $i -lt ${#arr1[@]} ] && [ $j -lt ${#arr2[@]} ]; do
if [ ${arr1[$i]} -le ${arr2[$j]} ]; then
result+=(${arr1[$i]} )
((i++))
else
result+=(${arr2[$j]} )
((j++))
fi
done
while [ $i -lt ${#arr1[@]} ]; do
result+=(${arr1[$i]} )
((i++))
done
while [ $j -lt ${#arr2[@]} ]; do
result+=(${arr2[$j]} )
((j++))
done
echo "${result[@]} "
}
arr1=(1 2 3)
arr2=(4 5 6)
echo "Merged: $(merge_arrays "${arr1[@]} " "${arr2[@]} " ) "
sorted1=(1 3 5 7)
sorted2=(2 4 6 8)
echo "Merged sorted: $(merge_sorted sorted1 sorted2) " 46 How interviewers ask it “Can you convert string to number in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Convert a string to a number using arithmetic expansion or bc .
Convert a string to a number using arithmetic expansion or bc.
Integer : $((var))Float : echo "$var" | bcSafe : ${var//[^0-9.-]/}Error handling : 2>/dev/null ShellCopy
#!/bin/bash
string_to_number () {
echo "$1 " | bc 2>/dev/null || echo 0
}
string_to_int () {
echo "${1//[^0-9-]/} " | bc
}
string_to_float () {
echo "$1 " | bc -l 2>/dev/null || echo 0
}
strings=("42" "3.14" "hello" "123" "45.67" )
for s in "${strings[@]} " ; do
echo "" $s " -> int: $(string_to_int "$s " ) , float: $(string_to_float "$s " ) "
done 47 How interviewers ask it “Quick coding-round task — loop through dictionary in Shell Scripting. How would you handle the edge cases?”
Coding Shell Scripting
Quick answer Iterate through an associative array using for key in "{!dict[@]}" .
Iterate through an associative array using for key in "{!dict[@]}".
Keys : {!dict[@]}Values : {dict[$key]}Find key : Check if key existsReturn : {dict[$key]:-default} ShellCopy
#!/bin/bash
declare -A data
data[name]="Alice"
data[age]=25
data[city]="NYC"
loop_dict () {
for key in "${!data[@]} " ; do
echo "$key => ${data[$key]} "
done
}
find_key () {
local key=$1
echo "${data[$key]:-Not found} "
}
echo "Dictionary:"
loop_dict
echo ""
name=$(find_key "name" )
echo "Name: $name "
country=$(find_key "country" )
echo "Country: $country " 48 How interviewers ask it “Show me delay function execution in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Delay execution using sleep or background processes.
Blocking : sleep $seconds; commandAsync : (sleep $seconds; command) &Callback : Function after delayTimer : Use at or cron ShellCopy
#!/bin/bash
delay_seconds () {
sleep "$1 "
shift
"$@ "
}
delay_async () {
(
sleep "$1 "
shift
"$@ "
) &
}
delayed_print () {
echo "Starting delay of $2 seconds"
delay_seconds "$2 " echo "$1 "
}
echo "Delayed execution examples:"
delayed_print "After 2 seconds" 2
echo "Main script continues" 49 How interviewers ask it “Show me HTTP GET request in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Make HTTP requests using curl or wget .
Make HTTP requests using curl or wget.
curl : curl -s URLwget : wget -qO- URLHeaders : curl -H "Header: value"Error handling : curl -f ShellCopy
#!/bin/bash
fetch_data () {
curl -s "$1 "
}
fetch_data_wget () {
wget -qO- "$1 "
}
post_data () {
curl -s -X POST -H "Content-Type: application/json" -d "$2 " "$1 "
}
curl -s -H "User-Agent: Bash" "https://api.github.com"
if ! result=$(curl -s -f "https://api.github.com" 2>/dev/null); then
echo "Error fetching data"
fi 50 How interviewers ask it “Can you create a promise-like task in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Create promise-like behavior using background processes and wait .
Create promise-like behavior using background processes and wait.
Promise : (sleep 1; echo "Success") &Wait : wait $pidCheck : $? for success/failureChain : Sequential waits ShellCopy
#!/bin/bash
create_promise () {
local should_resolve=$1
local result=""
(
sleep 1
if [ "$should_resolve " = true ]; then
echo "Success!"
else
echo "Failed!"
exit 1
fi
) &
echo $!
}
pid=$(create_promise true )
wait $pid
if [ $? -eq 0 ]; then
echo "Promise resolved"
else
echo "Promise rejected"
fi
pid=$(create_promise false )
wait $pid
if [ $? -eq 0 ]; then
echo "Promise resolved"
else
echo "Promise rejected"
fi
chain_promises () {
local p1=$1
local p2=$2
(
wait $p1
if [ $? -eq 0 ]; then
wait $p2
if [ $? -eq 0 ]; then
echo "Both completed"
else
echo "Second failed"
fi
else
echo "First failed"
fi
) &
}
promise_all () {
local pids=("$@ " )
for pid in "${pids[@]} " ; do
wait $pid
if [ $? -ne 0 ]; then
echo "Failed"
return 1
fi
done
echo "All succeeded"
}51 How interviewers ask it “Show me factorial in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Calculate factorial using recursion or iteration.
Recursive : factorial() { [ $1 -le 1 ] && echo 1 || echo $(( $1 * $(factorial $(( $1 - 1 )) ) )); }Iterative : for ((i=2; i<=n; i++)); do result=$((result * i)); doneEdge cases : 0! = 1Time : O(n) ShellCopy
#!/bin/bash
factorial () {
if [ $1 -le 1 ]; then
echo 1
else
local n=$1
local sub=$(factorial $((n - 1 )))
echo $((n * sub))
fi
}
factorial_iterative () {
local n=$1
local result=1
for ((i=2 ; i<=n; i++)); do
result=$((result * i))
done
echo $result
}
n=5
echo "Factorial of $n :"
echo "Recursive: $(factorial $n) "
echo "Iterative: $(factorial_iterative $n) " 52 How interviewers ask it “Show me fibonacci in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Calculate Fibonacci numbers using recursion, iteration, or memoization.
Recursive : fib() { [ $1 -le 1 ] && echo $1 || echo $(( $(fib $(( $1 - 1 )) ) + $(fib $(( $1 - 2 )) ) )); }Iterative : for ((i=2; i<=n; i++)); do c=$((a+b)); a=$b; b=$c; doneMemoized : Use cache fileTime : O(n) iterative ShellCopy
#!/bin/bash
fibonacci () {
if [ $1 -le 1 ]; then
echo $1
else
local n=$1
local a=$(fibonacci $((n - 1 )))
local b=$(fibonacci $((n - 2 )))
echo $((a + b))
fi
}
fibonacci_iterative () {
local n=$1
if [ $n -le 1 ]; then
echo $n
return
fi
local a=0 b=1
for ((i=2 ; i<=n; i++)); do
local c=$((a + b))
a=$b
b=$c
done
echo $b
}
fibonacci_memoized () {
local n=$1
local cache_file="/tmp/fib_cache_$$"
if [ -f "$cache_file " ] && grep -q "^$n :" "$cache_file " ; then
grep "^$n :" "$cache_file " | cut -d: -f2
return
fi
local result
if [ $n -le 1 ]; then
result=$n
else
local a=$(fibonacci_memoized $((n - 1 )))
local b=$(fibonacci_memoized $((n - 2 )))
result=$((a + b))
fi
echo "$n :$result " >> "$cache_file "
echo $result
}
trap 'rm -f /tmp/fib_cache_$$' EXIT
n=10
echo "Fibonacci of $n :"
echo "Recursive: $(fibonacci $n) "
echo "Iterative: $(fibonacci_iterative $n) "
echo "Memoized: $(fibonacci_memoized $n) " 53 How interviewers ask it “Show me fizzBuzz in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Print numbers with FizzBuzz logic using conditional statements.
If-else : if [ $((i % 15)) -eq 0 ]; then ...Case : case $((i % 15)) in 0) echo "FizzBuzz";; ...Array : Store resultsOutput : echo ShellCopy
#!/bin/bash
fizzbuzz () {
local n=$1
for ((i=1 ; i<=n; i++)); do
if [ $((i % 15 )) -eq 0 ]; then
echo "FizzBuzz"
elif [ $((i % 3 )) -eq 0 ]; then
echo "Fizz"
elif [ $((i % 5 )) -eq 0 ]; then
echo "Buzz"
else
echo $i
fi
done
}
fizzbuzz_array () {
local n=$1
local result=()
for ((i=1 ; i<=n; i++)); do
if [ $((i % 15 )) -eq 0 ]; then
result+=("FizzBuzz" )
elif [ $((i % 3 )) -eq 0 ]; then
result+=("Fizz" )
elif [ $((i % 5 )) -eq 0 ]; then
result+=("Buzz" )
else
result+=($i )
fi
done
echo "${result[@]} "
}
echo "FizzBuzz for 15:"
fizzbuzz 15
echo "FizzBuzz array:"
fizzbuzz_array 1554 How interviewers ask it “Quick coding-round task — find missing number in Shell Scripting. How would you handle the edge cases?”
Coding Shell Scripting
Quick answer Find missing number using sum formula or XOR operation.
Sum : $((n*(n+1)/2 - sum))XOR : xor_all ^ xor_arrTime : O(n)Edge cases : Empty array ShellCopy
#!/bin/bash
find_missing () {
local arr=("$@ " )
local n=$((${#arr[@]} + 1 ))
local total=$((n * (n + 1 ) / 2 ))
local sum =0
for num in "${arr[@]} " ; do
sum =$((sum + num))
done
echo $((total - sum))
}
find_missing_xor () {
local arr=("$@ " )
local n=$((${#arr[@]} + 1 ))
local xor_all=0
for ((i=1 ; i<=n; i++)); do
xor_all=$((xor_all ^ i))
done
local xor_arr=0
for num in "${arr[@]} " ; do
xor_arr=$((xor_arr ^ num))
done
echo $((xor_all ^ xor_arr))
}
arr=(1 2 4 5 6)
echo "Missing number: $(find_missing "${arr[@]} " ) "
echo "Missing number (XOR): $(find_missing_xor "${arr[@]} " ) " 55 How interviewers ask it “Can you find duplicates in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Find duplicates using associative arrays or sort | uniq -d .
Find duplicates using associative arrays or sort | uniq -d.
Associative array : Count occurrencessort : printf '%s\n' "{arr[@]}" | sort | uniq -dTime : O(n) or O(n log n)Returns : Duplicate values ShellCopy
#!/bin/bash
find_duplicates () {
local arr=("$@ " )
local seen=()
local dups=()
for item in "${arr[@]} " ; do
local found=0
for seen_item in "${seen[@]} " ; do
if [ "$seen_item " = "$item " ]; then
found=1
break
fi
done
if [ $found -eq 1 ]; then
local dup_found=0
for dup in "${dups[@]} " ; do
if [ "$dup " = "$item " ]; then
dup_found=1
break
fi
done
if [ $dup_found -eq 0 ]; then
dups+=("$item " )
fi
else
seen+=("$item " )
fi
done
echo "${dups[@]} "
}
find_duplicates_count () {
local arr=("$@ " )
declare -A count
for item in "${arr[@]} " ; do
count[$item ]=$((count[$item ] + 1 ))
done
local dups=()
for key in "${!count[@]} " ; do
if [ ${count[$key]} -gt 1 ]; then
dups+=("$key " )
fi
done
echo "${dups[@]} "
}
arr=(1 2 3 2 4 3 5 6 5)
echo "Original: ${arr[@]} "
echo "Duplicates: $(find_duplicates "${arr[@]} " ) "
echo "Duplicates (count): $(find_duplicates_count "${arr[@]} " ) " 56 How interviewers ask it “Can you sum of array in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Sum array elements using a loop or awk .
Sum array elements using a loop or awk.
Loop : sum=0; for num in "{arr[@]}"; do sum=$((sum + num)); doneawk : printf '%s\n' "{arr[@]}" | awk '{sum+=$1} END {print sum}'Empty : Returns 0Time : O(n) ShellCopy
#!/bin/bash
sum_array () {
local sum =0
for num in "$@ " ; do
sum =$((sum + num))
done
echo $sum
}
sum_array_manual () {
local arr=("$@ " )
local sum =0
for ((i=0 ; i<${#arr[@]} ; i++)); do
sum =$((sum + arr[i]))
done
echo $sum
}
arr=(1 2 3 4 5)
echo "Array: ${arr[@]} "
echo "Sum: $(sum_array "${arr[@]} " ) "
echo "Sum (manual): $(sum_array_manual "${arr[@]} " ) " 57 How interviewers ask it “Show me average of array in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Calculate average by dividing sum by length.
Method : sum=0; count=0; for num in "{arr[@]}"; do sum=$((sum + num)); count=$((count + 1)); done; echo "scale=2; $sum / $count" | bcInteger : echo $((sum / count))Empty : Return 0Time : O(n) ShellCopy
#!/bin/bash
average_array () {
local sum =0
local count=0
for num in "$@ " ; do
sum =$((sum + num))
count=$((count + 1 ))
done
echo "scale=2; $sum / $count " | bc
}
average_integer () {
local sum =0
local count=0
for num in "$@ " ; do
sum =$((sum + num))
count=$((count + 1 ))
done
echo $((sum / count))
}
int_arr=(1 2 3 4 5)
float_arr=(1.0 2.0 3.0 4.0 5.0)
echo "Average (int array): $(average_array "${int_arr[@]} " ) "
echo "Average (integer): $(average_integer "${int_arr[@]} " ) " 58 How interviewers ask it “Quick coding-round task — sort ascending in Shell Scripting. How would you handle the edge cases?”
Coding Shell Scripting
Quick answer Sort arrays using sort -n or bubble sort.
sort : printf '%s\n' "{arr[@]}" | sort -nBubble sort : Custom implementationTime : O(n log n) with sortIn-place : IFS=$'\n' read -ra sorted <<< "$(printf '%s\n' "{arr[@]}" | sort -n)" ShellCopy
#!/bin/bash
sort_ascending () {
printf '%s
' "$@ " | sort -n
}
sort_ascending_inplace () {
local arr=("$@ " )
IFS=$'\n' read -ra sorted <<< "$(printf '%s
' "${arr[@]} " | sort -n) "
arr=("${sorted[@]} " )
}
arr=(5 2 8 1 9 3)
echo "Original: ${arr[@]} "
sorted=($(sort_ascending "${arr[@]} " ))
echo "Sorted ascending: ${sorted[@]} "
sort_ascending_inplace "${arr[@]} "
echo "Sorted in-place: ${arr[@]} " 59 How interviewers ask it “Live coding: Sort descending in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Sort descending using sort -nr or custom sort.
sort : printf '%s\n' "{arr[@]}" | sort -nrBubble sort : Reverse comparisonTime : O(n log n) with sortIn-place : Similar to ascending ShellCopy
#!/bin/bash
sort_descending () {
printf '%s
' "$@ " | sort -nr
}
sort_descending_inplace () {
local arr=("$@ " )
IFS=$'\n' read -ra sorted <<< "$(printf '%s
' "${arr[@]} " | sort -nr) "
arr=("${sorted[@]} " )
}
arr=(5 2 8 1 9 3)
echo "Original: ${arr[@]} "
sorted=($(sort_descending "${arr[@]} " ))
echo "Sorted descending: ${sorted[@]} "
sort_descending_inplace "${arr[@]} "
echo "Sorted in-place: ${arr[@]} " 60 How interviewers ask it “Live coding: Flatten nested array in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Flatten nested arrays using recursion or echo .
Flatten nested arrays using recursion or echo.
Recursive : flatten() { for item in "$@"; do ...; done }Simple : echo "$@"Time : O(n)Depth : Handles nested structures ShellCopy
#!/bin/bash
flatten () {
local result=()
for item in "$@ " ; do
if [[ "$item " =~ ^[0-9]+$ ]]; then
result+=("$item " )
else
local sub_result=($(flatten $item ))
result+=("${sub_result[@]} " )
fi
done
echo "${result[@]} "
}
flatten_simple () {
echo "$@ " | tr ' ' '\n' | sort -u
}
nested="1 2 3 4 5 6 7 8 9 10"
deeper="1 2 3 4 5 6 7 8 9 10"
echo "Nested: $nested "
echo "Flatten: $(flatten_simple "$nested " ) " 61 How interviewers ask it “Show me chunk array in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Split an array into chunks of a specified size.
Method : chunk_array() { local size=$1; shift; ... }Loop : while [ $i -lt {#arr[@]} ]; do ...Use case : Batch processingTime : O(n) ShellCopy
#!/bin/bash
chunk_array () {
local arr=("$@ " )
local size=$1
shift
local result=()
local chunk=()
local count=0
for item in "$@ " ; do
chunk+=("$item " )
count=$((count + 1 ))
if [ $count -eq $size ]; then
result+=("${chunk[@]} " )
chunk=()
count=0
fi
done
if [ ${#chunk[@]} -gt 0 ]; then
result+=("${chunk[@]} " )
fi
echo "${result[@]} "
}
chunk_array_manual () {
local arr=("$@ " )
local size=$1
shift
local result=()
local i=0
while [ $i -lt ${#arr[@]} ]; do
local end=$((i + size))
if [ $end -gt ${#arr[@]} ]; then
end=${#arr[@]}
fi
local chunk=()
for ((j=i; j<end; j++)); do
chunk+=("${arr[$j]} " )
done
result+=("${chunk[@]} " )
i=$end
done
echo "${result[@]} "
}
arr=(1 2 3 4 5 6 7 8 9 10)
echo "Original: ${arr[@]} "
echo "Chunk (size 3):"
chunk_array 3 "${arr[@]} " 62 How interviewers ask it “Show me binary search in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement binary search on a sorted array.
Method : while [ $left -le $right ]; do mid=$(((left+right)/2)); ...Precondition : Sorted arrayTime : O(log n)Returns : Index or -1 ShellCopy
#!/bin/bash
binary_search () {
local arr=("$@ " )
local target=${arr[-1]}
unset 'arr[-1]'
local left=0
local right=$((${#arr[@]} - 1 ))
while [ $left -le $right ]; do
local mid=$(((left + right) / 2 ))
if [ ${arr[$mid]} -eq $target ]; then
echo $mid
return
elif [ ${arr[$mid]} -lt $target ]; then
left=$((mid + 1 ))
else
right=$((mid - 1 ))
fi
done
echo -1
}
arr=(1 2 3 4 5 6 7)
target=5
index=$(binary_search "${arr[@]} " $target )
echo "Found $target at index: $index "
target2=8
index2=$(binary_search "${arr[@]} " $target2 )
echo "Found $target2 at index: $index2 " 63 How interviewers ask it “Show me quick sort in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement quick sort with pivot and recursion.
Recursive : quick_sort() { ... }Pivot : First elementPartition : Split into smaller/largerTime : O(n log n) average ShellCopy
#!/bin/bash
quick_sort () {
local arr=("$@ " )
if [ ${#arr[@]} -le 1 ]; then
echo "${arr[@]} "
return
fi
local pivot=${arr[0]}
local left=()
local right=()
for ((i=1 ; i<${#arr[@]} ; i++)); do
if [ ${arr[$i]} -lt $pivot ]; then
left+=(${arr[$i]} )
else
right+=(${arr[$i]} )
fi
done
local sorted_left=($(quick_sort "${left[@]} " ))
local sorted_right=($(quick_sort "${right[@]} " ))
echo "${sorted_left[@]} $pivot ${sorted_right[@]} "
}
arr=(5 3 8 4 2 7 1 6)
echo "Original: ${arr[@]} "
sorted=($(quick_sort "${arr[@]} " ))
echo "Quick sort: ${sorted[@]} " 64 How interviewers ask it “Can you merge sort in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Implement merge sort with divide and conquer.
Divide : Split in halfMerge : Combine sorted halvesTime : O(n log n)Space : O(n) ShellCopy
#!/bin/bash
merge () {
local left=("$@ " )
local right=()
local mid=$((${#left[@]} / 2 ))
for ((i=0 ; i<mid; i++)); do
right+=("${left[$i]} " )
done
left=("${left[@]:mid} " )
local result=()
local i=0 j=0
while [ $i -lt ${#left[@]} ] && [ $j -lt ${#right[@]} ]; do
if [ ${left[$i]} -le ${right[$j]} ]; then
result+=(${left[$i]} )
i=$((i + 1 ))
else
result+=(${right[$j]} )
j=$((j + 1 ))
fi
done
while [ $i -lt ${#left[@]} ]; do
result+=(${left[$i]} )
i=$((i + 1 ))
done
while [ $j -lt ${#right[@]} ]; do
result+=(${right[$j]} )
j=$((j + 1 ))
done
echo "${result[@]} "
}
merge_sort () {
local arr=("$@ " )
if [ ${#arr[@]} -le 1 ]; then
echo "${arr[@]} "
return
fi
local mid=$((${#left[@]} / 2 ))
local left=()
local right=()
for ((i=0 ; i<mid; i++)); do
left+=(${arr[$i]} )
done
for ((i=mid; i<${#arr[@]} ; i++)); do
right+=(${arr[$i]} )
done
local sorted_left=($(merge_sort "${left[@]} " ))
local sorted_right=($(merge_sort "${right[@]} " ))
echo $(merge "${sorted_left[@]} " "${sorted_right[@]} " )
}
arr=(5 3 8 4 2 7 1 6)
echo "Original: ${arr[@]} "
sorted=($(merge_sort "${arr[@]} " ))
echo "Merge sort: ${sorted[@]} " 65 How interviewers ask it “Show me bubble sort in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement bubble sort with optimization.
Basic : for ((i=0; i<n-1; i++)); do for ((j=0; j<n-i-1; j++)); do if [ {arr[$j]} -gt {arr[$j+1]} ]; then swap; fi; done; doneOptimized : Track swapsTime : O(n²)Use case : Small arrays ShellCopy
#!/bin/bash
bubble_sort () {
local arr=("$@ " )
local n=${#arr[@]}
for ((i=0 ; i<n-1 ; i++)); do
for ((j=0 ; j<n-i-1 ; j++)); do
if [ ${arr[$j]} -gt ${arr[$j+1]} ]; then
local temp=${arr[$j]}
arr[$j ]=${arr[$j+1]}
arr[$j +1]=$temp
fi
done
done
echo "${arr[@]} "
}
bubble_sort_optimized () {
local arr=("$@ " )
local n=${#arr[@]}
for ((i=0 ; i<n-1 ; i++)); do
local swapped=0
for ((j=0 ; j<n-i-1 ; j++)); do
if [ ${arr[$j]} -gt ${arr[$j+1]} ]; then
local temp=${arr[$j]}
arr[$j ]=${arr[$j+1]}
arr[$j +1]=$temp
swapped=1
fi
done
if [ $swapped -eq 0 ]; then
break
fi
done
echo "${arr[@]} "
}
arr=(5 3 8 4 2 7 1 6)
echo "Original: ${arr[@]} "
echo "Bubble sort: $(bubble_sort "${arr[@]} " ) "
echo "Bubble sort optimized: $(bubble_sort_optimized "${arr[@]} " ) " 66 How interviewers ask it “Show me intersection of arrays in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Find common elements between two arrays.
Method : for item1 in "{arr1[@]}"; do for item2 in "{arr2[@]}"; do ...Alternative : Use associative arrayTime : O(n*m)Unique : Remove duplicates ShellCopy
#!/bin/bash
intersection () {
local arr1=("${!1} " )
local arr2=("${!2} " )
local result=()
for item1 in "${arr1[@]} " ; do
for item2 in "${arr2[@]} " ; do
if [ "$item1 " = "$item2 " ]; then
local found=0
for res in "${result[@]} " ; do
if [ "$res " = "$item1 " ]; then
found=1
break
fi
done
if [ $found -eq 0 ]; then
result+=("$item1 " )
fi
break
fi
done
done
echo "${result[@]} "
}
arr1=(apple banana orange grape kiwi)
arr2=(banana kiwi mango grape)
echo "Intersection: $(intersection arr1 arr2) "
ints1=(1 2 3 4 5)
ints2=(4 5 6 7 8)
echo "Intersection (ints): $(intersection ints1 ints2) " 67 How interviewers ask it “Show me union of arrays in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Combine arrays with unique elements.
Method : result=("{arr1[@]}"); for item in "{arr2[@]}"; do ...Alternative : printf '%s\n' "{arr1[@]}" "{arr2[@]}" | sort -uTime : O(n*m) or O(n log n) with sortPreserve order : Manual method ShellCopy
#!/bin/bash
union () {
local arr1=("${!1} " )
local arr2=("${!2} " )
local result=("${arr1[@]} " )
for item in "${arr2[@]} " ; do
local found=0
for res in "${result[@]} " ; do
if [ "$res " = "$item " ]; then
found=1
break
fi
done
if [ $found -eq 0 ]; then
result+=("$item " )
fi
done
echo "${result[@]} "
}
arr1=(apple banana orange)
arr2=(orange grape kiwi)
echo "Union: $(union arr1 arr2) "
ints1=(1 2 3 4)
ints2=(4 5 6 7)
echo "Union (ints): $(union ints1 ints2) " 68 How interviewers ask it “Our team relies on difference of arrays in Shell Scripting. What should every engineer here know about it?”
Coding Shell Scripting
Quick answer Find elements in first array not in second.
Method : for item in "{arr1[@]}"; do found=0; for item2 in "{arr2[@]}"; do ...Symmetric : Both directionsTime : O(n*m)Returns : Difference ShellCopy
#!/bin/bash
difference () {
local arr1=("${!1} " )
local arr2=("${!2} " )
local result=()
for item in "${arr1[@]} " ; do
local found=0
for item2 in "${arr2[@]} " ; do
if [ "$item " = "$item2 " ]; then
found=1
break
fi
done
if [ $found -eq 0 ]; then
result+=("$item " )
fi
done
echo "${result[@]} "
}
symmetric_difference () {
local arr1=("${!1} " )
local arr2=("${!2} " )
local diff1=($(difference arr1 arr2))
local diff2=($(difference arr2 arr1))
echo "${diff1[@]} ${diff2[@]} "
}
arr1=(apple banana orange grape)
arr2=(banana kiwi grape)
echo "Difference: $(difference arr1 arr2) "
echo "Symmetric difference: $(symmetric_difference arr1 arr2) "
ints1=(1 2 3 4 5)
ints2=(4 5 6 7 8)
echo "Difference (ints): $(difference ints1 ints2) " 69 How interviewers ask it “Live coding: Group by property in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Group data by a property using associative arrays.
Method : declare -A groups; for item in ...; do key="{item#*:}"; groups[$key]="{groups[$key]} $item"; doneUse case : Data aggregationTime : O(n)Output : Grouped data ShellCopy
#!/bin/bash
declare -A people
people[1]="Alice:25:NYC"
people[2]="Bob:30:LA"
people[3]="Charlie:25:NYC"
people[4]="David:35:Chicago"
people[5]="Eve:30:LA"
group_by_age () {
local groups =()
for key in "${!people[@]} " ; do
local person=${people[$key]}
IFS=':' read -r name age city <<< "$person "
local key="$age "
groups +=("$key :$name " )
done
echo "${groups[@]} "
}
group_by_city () {
local groups =()
for key in "${!people[@]} " ; do
local person=${people[$key]}
IFS=':' read -r name age city <<< "$person "
local key="$city "
groups +=("$key :$name " )
done
echo "${groups[@]} "
}
echo "Group by age:"
for group in $(group_by_age); do
IFS=':' read -r age name <<< "$group "
echo "Age $age : $name "
done
echo "Group by city:"
for group in $(group_by_city); do
IFS=':' read -r city name <<< "$group "
echo "City $city : $name "
done 70 How interviewers ask it “Live coding: Deep clone in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Create a deep copy of an array or associative array.
Array : clone=("{original[@]}")Associative : for key in "{!original[@]}"; do clone[$key]="{original[$key]}"; doneNested : Recursive copyTime : O(n) ShellCopy
#!/bin/bash
deep_clone () {
local var_name=$1
local clone_name="${var_name} _clone"
eval "$clone_name =" ${$var_name[@]} ""
eval "declare -a $clone_name =(${$var_name[@]} )"
}
original=(1 2 3)
deep_clone original
eval "cloned=(${original_clone[@]} )"
echo "Original: ${original[@]} "
echo "Cloned: ${cloned[@]} "
deep_clone_assoc () {
local var_name=$1
local clone_name="${var_name} _clone"
eval "declare -A $clone_name "
eval "for key in " ${!$var_name[@]} "; do $clone_name [$key ]=" ${$var_name[$key]} "; done"
}
declare -A map
map[name]="Alice"
map[age]=25
deep_clone_assoc map
eval "declare -A map_clone"
eval "for key in " ${!map_clone[@]} "; do echo " $key => ${map_clone[$key]} "; done" 71 How interviewers ask it “Show me immutable update in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Perform immutable updates by copying and modifying.
Method : clone=("{original[@]}"); clone[$index]="$value"Nested : Copy and update nestedReturn : New arrayUse case : State management ShellCopy
#!/bin/bash
update_immutable () {
local var_name=$1
local path=$2
local value=$3
eval "local clone=(${$var_name[@]} )"
eval "clone[$path ]=" $value ""
echo "${clone[@]} "
}
update_nested () {
local var_name=$1
local key=$2
local value=$3
eval "declare -A clone"
eval "for k in " ${!$var_name[@]} "; do clone[$k ]=" ${$var_name[$k]} "; done"
eval "clone[$key ]=" $value ""
echo "${clone[@]} "
}
state=(name Alice age 25)
new_state=($(update_immutable state 1 Bob))
echo "Original: ${state[@]} "
echo "Updated: ${new_state[@]} "
declare -A person
person[name]="Alice"
person[age]=25
person[city]="NYC"
eval "new_person=($(update_nested person age 26) )"
echo "Original: ${person[@]} "
echo "Updated: ${new_person[@]} " 72 How interviewers ask it “Show me pipe function in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement pipe for left-to-right function composition.
Method : pipe() { value=$1; shift; for func in "$@"; do value=$($func "$value"); done; echo "$value"; }Direction : Left to rightUse case : Function chainingImplementation : Loop functions ShellCopy
#!/bin/bash
pipe () {
local value=$1
shift
for func in "$@ " ; do
value=$($func "$value " )
done
echo "$value "
}
double () { echo $(( $1 * 2 )); }
add_ten () { echo $(( $1 + 10 )); }
square () { echo $(( $1 * $1 )); }
result=$(pipe 5 double add_ten square)
echo "Pipe: $result "
double_pipe () { while read -r x; do echo $((x * 2 )); done ; }
add_ten_pipe () { while read -r x; do echo $((x + 10 )); done ; }
square_pipe () { while read -r x; do echo $((x * x)); done ; }
result2=$(echo 5 | double_pipe | add_ten_pipe | square_pipe)
echo "Pipeline: $result2 " 73 How interviewers ask it “Show me compose function in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement compose for right‑to‑left function composition.
Method :compose() { result=$1; shift; for ((i=${#@}-1; i>=0; i--)); do result=${@:$i:1} "$result"); done; echo "$result"; }Direction : Right to leftUse case : Function compositionAlternative : compose_alt ShellCopy
#!/bin/bash
compose () {
local funcs=("$@ " )
local result=$1
shift
for ((i=${#funcs[@]} -1 ; i>=0 ; i--)); do
result=$(${funcs[$i]} "$result " )
done
echo "$result "
}
double () { echo $(( $1 * 2 )); }
add_ten () { echo $(( $1 + 10 )); }
square () { echo $(( $1 * $1 )); }
result=$(compose 5 double add_ten square)
echo "Composed: $result "
compose_alt () {
local funcs=("$@ " )
local value=$1
shift
for func in "${funcs[@]} " ; do
value=$($func "$value " )
done
echo "$value "
}
result2=$(compose_alt 5 square add_ten double)
echo "Composed alt: $result2 " 74 How interviewers ask it “Show me memoization in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement memoization using associative arrays.
Cache : declare -A cacheCheck : [[ -v cache[$key] ]]Store : cache[$key]="$result"File cache : Use temporary files ShellCopy
#!/bin/bash
declare -A memo_cache
memoize () {
local func=$1
local arg=$2
local cache_key="${func} _$arg "
if [ -n "${memo_cache[$cache_key]} " ]; then
echo "${memo_cache[$cache_key]} "
return
fi
local result=$($func $arg )
memo_cache[$cache_key ]=$result
echo $result
}
fib () {
if [ $1 -le 1 ]; then
echo $1
else
local a=$(memoize fib $(( $1 - 1 )))
local b=$(memoize fib $(( $1 - 2 )))
echo $((a + b))
fi
}
echo "Fibonacci(10): $(fib 10) "
echo "Fibonacci(10) again: $(fib 10) "
memoize_file () {
local func=$1
local arg=$2
local cache_dir="/tmp/memo_cache"
mkdir -p "$cache_dir "
local cache_file="$cache_dir /${func} _$arg "
if [ -f "$cache_file " ]; then
cat "$cache_file "
return
fi
local result=$($func $arg )
echo "$result " > "$cache_file "
echo $result
}75 How interviewers ask it “Show me once function in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement once function that ensures a function is called only once.
Flag : called=0Check : if [ $called -eq 0 ]; then ...Result : Cache resultReset : Reset flag ShellCopy
#!/bin/bash
declare -A once_called
declare -A once_results
once () {
local func=$1
local arg=$2
local key="${func} _$arg "
if [ -n "${once_called[$key]} " ]; then
echo "${once_results[$key]} "
return
fi
once_called[$key ]=1
local result=$($func $arg )
once_results[$key ]=$result
echo $result
}
initialize () {
echo "Initialized with $1 "
echo $(( $1 * 2 ))
}
echo "First: $(once initialize 10) "
echo "Second: $(once initialize 20) "
once_with_reset () {
local func=$1
local arg=$2
local key="${func} _$arg "
if [ -n "${once_called[$key]} " ]; then
echo "${once_results[$key]} "
return
fi
once_called[$key ]=1
local result=$($func $arg )
once_results[$key ]=$result
echo $result
}
reset_once () {
local func=$1
local arg=$2
local key="${func} _$arg "
unset once_called[$key ]
unset once_results[$key ]
}
init () {
echo "Initialized with $1 "
echo $(( $1 * 2 ))
}
echo "First: $(once_with_reset init 10) "
reset_once init 10
echo "After reset: $(once_with_reset init 20) " 76 How interviewers ask it “Can you debounce with leading edge in Shell Scripting? Then tell me the time and space complexity.”
Coding Shell Scripting
Quick answer Implement debounce with leading edge using timers.
Last call : Track timeExecute : If enough time passedTimeout : Schedule delayed executionUse case : Rate limiting ShellCopy
#!/bin/bash
declare -A debounce_last_call
declare -A debounce_timeout
debounce_leading () {
local func=$1
local delay=$2
local arg=$3
local key="${func} _$arg "
local now=$(date +%s)
if [ -z "${debounce_last_call[$key]} " ] || [ $((now - debounce_last_call[$key ])) -ge $delay ]; then
debounce_last_call[$key ]=$now
$func $arg
else
if [ -z "${debounce_timeout[$key]} " ]; then
(
sleep $((delay - (now - debounce_last_call[$key ])))
debounce_last_call[$key ]=$(date +%s)
$func $arg
unset debounce_timeout[$key ]
) &
debounce_timeout[$key ]=1
fi
fi
}
process () {
echo "Processing: $1 "
}
debounce_leading process 2 "value1"
debounce_leading process 2 "value2"
sleep 3
debounce_leading process 2 "value3" 77 How interviewers ask it “Live coding: Throttle with leading edge in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Implement throttle with leading edge by checking time since last call.
Last call : Track timeExecute : If enough time passedTrailing : Schedule pending executionUse case : Scroll events ShellCopy
#!/bin/bash
declare -A throttle_last_call
throttle_leading () {
local func=$1
local delay=$2
local arg=$3
local key="${func} _$arg "
local now=$(date +%s)
if [ -z "${throttle_last_call[$key]} " ] || [ $((now - throttle_last_call[$key ])) -ge $delay ]; then
throttle_last_call[$key ]=$now
$func $arg
fi
}
process () {
echo "Processing: $1 "
}
throttle_leading process 2 "value1"
throttle_leading process 2 "value2"
sleep 3
throttle_leading process 2 "value3"
declare -A throttle_pending
declare -A throttle_timer
throttle_trailing () {
local func=$1
local delay=$2
local arg=$3
local key="${func} _$arg "
local now=$(date +%s)
if [ -z "${throttle_last_call[$key]} " ] || [ $((now - throttle_last_call[$key ])) -ge $delay ]; then
throttle_last_call[$key ]=$now
$func $arg
else
throttle_pending[$key ]=$arg
if [ -z "${throttle_timer[$key]} " ]; then
local remaining=$((delay - (now - throttle_last_call[$key ])))
(
sleep $remaining
throttle_last_call[$key ]=$(date +%s)
if [ -n "${throttle_pending[$key]} " ]; then
$func ${throttle_pending[$key]}
unset throttle_pending[$key ]
fi
unset throttle_timer[$key ]
) &
throttle_timer[$key ]=1
fi
fi
}78 How interviewers ask it “Live coding: Deep equal in Shell Scripting. Talk me through your approach first.”
Coding Shell Scripting
Quick answer Implement deep equality for arrays and associative arrays.
Method : deep_equal() { local -n arr1=$1; local -n arr2=$2; ... }Length : Must be equalElements : Compare eachTypes : Check array types ShellCopy
#!/bin/bash
deep_equal () {
if [ "$1 " = "$2 " ]; then
return 0
fi
local type1=$(declare -p "$1 " 2>/dev/null)
local type2=$(declare -p "$2 " 2>/dev/null)
if [ "$type1 " != "$type2 " ]; then
return 1
fi
eval "local arr1=(${$1[@]} )"
eval "local arr2=(${$2[@]} )"
if [ ${#arr1[@]} -ne ${#arr2[@]} ]; then
return 1
fi
for ((i=0 ; i<${#arr1[@]} ; i++)); do
if [ "${arr1[$i]} " != "${arr2[$i]} " ]; then
return 1
fi
done
return 0
}
arr1=(1 2 3)
arr2=(1 2 3)
arr3=(1 2 4)
if deep_equal arr1 arr2; then
echo "arr1 == arr2"
else
echo "arr1 != arr2"
fi
if deep_equal arr1 arr3; then
echo "arr1 == arr3"
else
echo "arr1 != arr3"
fi
deep_equal_assoc () {
local -n arr1=$1
local -n arr2=$2
if [ ${#arr1[@]} -ne ${#arr2[@]} ]; then
return 1
fi
for key in "${!arr1[@]} " ; do
if [ "${arr1[$key]} " != "${arr2[$key]} " ]; then
return 1
fi
done
return 0
}
declare -A map1 map2 map3
map1[name]="Alice" ; map1[age]=25
map2[name]="Alice" ; map2[age]=25
map3[name]="Alice" ; map3[age]=26
if deep_equal_assoc map1 map2; then
echo "map1 == map2"
fi
if deep_equal_assoc map1 map3; then
echo "map1 == map3"
fi 79 How interviewers ask it “Show me observable pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement observable pattern with subscribers and notification.
Subscribers : Associative arraySubscribe : subscribers[$id]="$callback"Notify : for id in "{!subscribers[@]}"; do {subscribers[$id]} "$data"; doneStateful : Track state ShellCopy
#!/bin/bash
declare -A subscribers
observable () {
local action=$1
shift
case $action in
subscribe)
local id =$1
local callback=$2
subscribers[$id ]=$callback
;;
unsubscribe)
local id =$1
unset subscribers[$id ]
;;
notify)
local data=$1
for id in "${!subscribers[@]} " ; do
${subscribers[$id]} "$data "
done
;;
esac
}
declare -A stateful_subscribers
stateful_observable () {
local action=$1
shift
case $action in
subscribe)
local id =$1
local callback=$2
stateful_subscribers[$id ]=$callback
;;
set_state)
local data=$1
state=$data
for id in "${!stateful_subscribers[@]} " ; do
${stateful_subscribers[$id]} "$data "
done
;;
get_state)
echo "$state "
;;
esac
}
observable subscribe "observer1" "echo 'Observer1: $1 '"
observable subscribe "observer2" "echo 'Observer2: $1 '"
observable notify "Hello, World!"
observable unsubscribe "observer1"
observable notify "Hello again!"
stateful_observable set_state "Initial"
stateful_observable subscribe "state_obs" "echo 'State changed to: $1 '"
stateful_observable set_state "New State" 80 How interviewers ask it “Show me singleton pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement singleton pattern using associative arrays or variables.
Instance : singleton_data[$class]="initialized"Check : if [ -z "{singleton_data[$class]}" ]; then ...Return : Existing instanceFactory : Create on demand ShellCopy
#!/bin/bash
declare -A singleton_data
get_singleton () {
local class=$1
if [ -z "${singleton_data[$class]} " ]; then
singleton_data[$class ]="initialized"
echo "Creating singleton for $class "
fi
echo "${singleton_data[$class]} "
}
declare -A singleton_instances
singleton () {
local class=$1
if [ -z "${singleton_instances[$class]} " ]; then
singleton_instances[$class ]="instance"
echo "Singleton $class created"
fi
echo "${singleton_instances[$class]} "
}
singleton_factory () {
local instance_var="singleton_${1} _instance"
if [ -z "${!instance_var} " ]; then
eval "$instance_var ='created'"
echo "Singleton created: $1 "
fi
eval "echo $$instance_var "
}
get_singleton "config"
get_singleton "config"
singleton "database"
singleton "database"
singleton_factory "logger"
singleton_factory "logger"
declare -A singleton_store
singleton_store_init () {
local name=$1
if [ -z "${singleton_store[$name]} " ]; then
singleton_store[$name ]="{}"
echo "Store $name initialized"
fi
echo "${singleton_store[$name]} "
}
singleton_store_set () {
local name=$1
local key=$2
local value=$3
local data=$(singleton_store_init "$name " )
eval "declare -A temp"
eval "temp=($data )"
temp[$key ]=$value
local new_data=""
for k in "${!temp[@]} " ; do
new_data="$new_data $k =${temp[$k]} "
done
singleton_store[$name ]="$new_data "
}
singleton_store_get () {
local name=$1
local key=$2
local data=$(singleton_store_init "$name " )
eval "declare -A temp"
eval "temp=($data )"
echo "${temp[$key]:-} "
}81 How interviewers ask it “Show me factory pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement factory pattern for creating objects with different types.
Factory : create_user() { case $type in ... }Types : admin, guest, regularParameters : name, permissionsReturn : User string ShellCopy
#!/bin/bash
create_user () {
local type =$1
local name=$2
case $type in
admin)
echo "admin:$name "
;;
guest)
echo "guest:$name "
;;
*)
echo "regular:$name "
;;
esac
}
user_factory () {
local type =$1
local name=$2
if [ -z "$name " ]; then
echo "Error: Name is required" >&2
return 1
fi
create_user "$type " "$name "
}
create_user_with_permissions () {
local type =$1
local name=$2
local permissions=$3
case $type in
admin)
echo "admin:$name :$permissions "
;;
guest)
echo "guest:$name :"
;;
*)
echo "regular:$name :"
;;
esac
}
user1=$(create_user admin Alice)
user2=$(create_user guest Bob)
user3=$(create_user regular Charlie)
echo "$user1 "
echo "$user2 "
echo "$user3 "
user4=$(user_factory admin "Alice" )
user5=$(user_factory guest "Bob" )
echo "$user4 "
echo "$user5 " 82 How interviewers ask it “Show me strategy pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement strategy pattern with interchangeable strategies.
Strategies : FunctionsContext : payment_context() { case $strategy in ... }Execute : Call selected strategyDecorator : Add discount ShellCopy
#!/bin/bash
credit_card_payment () {
echo "Paid $1 with Credit Card"
}
paypal_payment () {
echo "Paid $1 with PayPal"
}
crypto_payment () {
echo "Paid $1 with Crypto"
}
payment_context () {
local strategy=$1
local amount=$2
case $strategy in
credit)
credit_card_payment "$amount "
;;
paypal)
paypal_payment "$amount "
;;
crypto)
crypto_payment "$amount "
;;
*)
echo "Unknown strategy"
;;
esac
}
discount_decorator () {
local strategy=$1
local discount=$2
local amount=$3
local discounted=$(echo "$amount * (1 - $discount )" | bc)
echo "Applied discount of $(($discount * 100) )%"
payment_context "$strategy " "$discounted "
}
payment_context credit 100
payment_context paypal 50
payment_context crypto 75
discount_decorator paypal 0.1 10083 How interviewers ask it “Show me observer pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement observer pattern with subject and observers.
Subject : subject() { case $action in attach|detach|notify) ... }Observers : Associative arrayAttach : Add observerNotify : Call all observers ShellCopy
#!/bin/bash
declare -A observers
subject () {
local action=$1
shift
case $action in
attach)
local id =$1
local callback=$2
observers[$id ]=$callback
;;
detach)
local id =$1
unset observers[$id ]
;;
notify)
local data=$1
for id in "${!observers[@]} " ; do
${observers[$id]} "$data "
done
;;
esac
}
declare -A stateful_observers
subject_state=""
stateful_subject () {
local action=$1
shift
case $action in
attach)
local id =$1
local callback=$2
stateful_observers[$id ]=$callback
;;
detach)
local id =$1
unset stateful_observers[$id ]
;;
set_state)
subject_state=$1
for id in "${!stateful_observers[@]} " ; do
${stateful_observers[$id]} "$subject_state "
done
;;
get_state)
echo "$subject_state "
;;
esac
}
subject attach "obs1" "echo 'Observer1: $1 '"
subject attach "obs2" "echo 'Observer2: $1 '"
subject notify "Hello, World!"
subject detach "obs1"
subject notify "Hello again!"
stateful_subject attach "state_obs" "echo 'State changed to: $1 '"
stateful_subject set_state "Initial State"
stateful_subject set_state "New State" 84 How interviewers ask it “Show me decorator pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement decorator pattern for adding features.
Component : basic_coffee() { echo "Coffee"; echo "5.0"; }Decorators : milk_decorator() { ... }Chaining : apply_decorators() { for decorator in "$@"; do ... }Composition : Nested calls ShellCopy
#!/bin/bash
basic_coffee () {
echo "Coffee"
echo "5.0"
}
milk_decorator () {
local desc=$1
local cost=$2
echo "$desc , Milk"
echo "$cost + 2.0" | bc
}
sugar_decorator () {
local desc=$1
local cost=$2
echo "$desc , Sugar"
echo "$cost + 1.0" | bc
}
caramel_decorator () {
local desc=$1
local cost=$2
echo "$desc , Caramel"
echo "$cost + 2.5" | bc
}
whipped_cream_decorator () {
local desc=$1
local cost=$2
echo "$desc , Whipped Cream"
echo "$cost + 1.5" | bc
}
apply_decorators () {
local desc="Coffee"
local cost="5.0"
for decorator in "$@ " ; do
case $decorator in
milk)
local result=$(milk_decorator "$desc " "$cost " )
desc=$(echo "$result " | head -1)
cost=$(echo "$result " | tail -1)
;;
sugar)
local result=$(sugar_decorator "$desc " "$cost " )
desc=$(echo "$result " | head -1)
cost=$(echo "$result " | tail -1)
;;
caramel)
local result=$(caramel_decorator "$desc " "$cost " )
desc=$(echo "$result " | head -1)
cost=$(echo "$result " | tail -1)
;;
whipped)
local result=$(whipped_cream_decorator "$desc " "$cost " )
desc=$(echo "$result " | head -1)
cost=$(echo "$result " | tail -1)
;;
esac
done
echo "$desc ($cost )"
}
basic_coffee
milk_decorator "Coffee" "5.0"
sugar_decorator "Coffee" "5.0"
apply_decorators milk sugar caramel whipped85 How interviewers ask it “Show me command pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement command pattern with execute, undo, and redo.
Command : add_command() { counter=$((counter + value)); command_history+=("add:$value"); }Undo : undo() { last={command_history[-1]}; ... }Redo : Re-execute commandsHistory : Store commands ShellCopy
#!/bin/bash
declare -a command_history
declare -a command_results
add_command () {
local value=$1
counter=$((counter + value))
command_history+=("add:$value " )
}
subtract_command () {
local value=$1
counter=$((counter - value))
command_history+=("subtract:$value " )
}
undo () {
if [ ${#command_history[@]} -gt 0 ]; then
local last=${command_history[-1]}
unset 'command_history[-1]'
local cmd=${last%:*}
local value=${last#*:}
case $cmd in
add) counter=$((counter - value));;
subtract) counter=$((counter + value));;
esac
fi
}
redo () {
local cmd=${command_history[-1]}
case $cmd in
add:*) add_command ${cmd#*:} ;;
subtract:*) subtract_command ${cmd#*:} ;;
esac
}
macro_command () {
for cmd in "$@ " ; do
case $cmd in
add:*) add_command ${cmd#*:} ;;
subtract:*) subtract_command ${cmd#*:} ;;
esac
done
}
counter=0
add_command 5
echo "Counter: $counter "
subtract_command 3
echo "Counter: $counter "
undo
echo "After undo: $counter "
macro_command "add:5" "add:5" "subtract:3"
echo "After macro: $counter " 86 How interviewers ask it “Show me memento pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement memento pattern for state capture and restoration.
Save : save_state() { mementos+=("$1"); }Restore : restore_state() { local state={mementos[-1]}; unset 'mementos[-1]'; echo "$state"; }Originator : Holds stateCaretaker : Manages mementos ShellCopy
#!/bin/bash
declare -a mementos
declare -a memento_states
save_state () {
local state=$1
mementos+=("$state " )
}
restore_state () {
if [ ${#mementos[@]} -gt 0 ]; then
local state=${mementos[-1]}
unset 'mementos[-1]'
echo "$state "
fi
}
originator_state=""
set_originator_state () {
originator_state=$1
save_state "$originator_state "
}
get_originator_state () {
echo "$originator_state "
}
set_originator_state 0
set_originator_state 1
set_originator_state 2
set_originator_state 3
echo "Current: $(get_originator_state) "
restored=$(restore_state)
echo "After undo: $restored "
restored=$(restore_state)
echo "After redo: $restored "
declare -a caretaker_mementos
declare -a caretaker_index
caretaker_save () {
local state=$1
caretaker_mementos+=("$state " )
}
caretaker_undo () {
if [ ${#caretaker_mementos[@]} -gt 0 ]; then
local state=${caretaker_mementos[-1]}
unset 'caretaker_mementos[-1]'
echo "$state "
fi
}
caretaker_redo () {
if [ ${#caretaker_mementos[@]} -gt 0 ]; then
echo "${caretaker_mementos[-1]} "
fi
}87 How interviewers ask it “Show me mediator pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement mediator pattern for centralized communication.
Mediator : mediator() { case $action in register|send) ... }Colleagues : Associate array of callbacksRegister : Add colleagueSend : Route messages ShellCopy
#!/bin/bash
declare -A mediator_colleagues
mediator () {
local action=$1
shift
case $action in
register)
local name=$1
local callback=$2
mediator_colleagues[$name ]=$callback
;;
send)
local message=$1
local sender=$2
for name in "${!mediator_colleagues[@]} " ; do
if [ "$name " != "$sender " ]; then
${mediator_colleagues[$name]} "$message "
fi
done
;;
esac
}
colleague () {
local name=$1
local receive_func=$2
echo "$name "
}
mediator register "Alice" "echo 'Alice received: $1 '"
mediator register "Bob" "echo 'Bob received: $1 '"
mediator register "Charlie" "echo 'Charlie received: $1 '"
mediator send "Hello everyone!" "Alice"
declare -A colleague_states
stateful_colleague () {
local name=$1
local state=$2
colleague_states[$name ]=$state
mediator register "$name " "echo '$name (state $state ) received: $1 '"
}
stateful_colleague "Alice" 0
stateful_colleague "Bob" 1
mediator send "Custom message" "Alice" 88 How interviewers ask it “Show me chain of responsibility in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement chain of responsibility with linked handlers.
Handlers : auth, logger, validatorChain : chain_handlers[$handler]="$next"Process : handler handle "$handler" "$request"Stop : On failure ShellCopy
#!/bin/bash
declare -A chain_handlers
handler () {
local action=$1
shift
case $action in
set_next)
local handler=$1
local next=$2
chain_handlers[$handler ]=$next
;;
handle)
local handler=$1
local request=$2
case $handler in
auth)
if echo "$request " | grep -q "token" ; then
echo "Authentication passed"
local next=${chain_handlers[$handler]}
if [ -n "$next " ]; then
handler handle "$next " "$request "
fi
else
echo "Authentication failed"
fi
;;
logger)
local url=$(echo "$request " | grep -o "url=[^&]*" | cut -d= -f2)
echo "Logging request: ${url:-unknown} "
local next=${chain_handlers[$handler]}
if [ -n "$next " ]; then
handler handle "$next " "$request "
fi
;;
validator)
if echo "$request " | grep -q "data" ; then
echo "Validation passed"
local next=${chain_handlers[$handler]}
if [ -n "$next " ]; then
handler handle "$next " "$request "
fi
else
echo "Validation failed"
fi
;;
ratelimit)
echo "Rate limit passed"
local next=${chain_handlers[$handler]}
if [ -n "$next " ]; then
handler handle "$next " "$request "
fi
;;
esac
;;
esac
}
handler set_next "auth" "logger"
handler set_next "logger" "validator"
handler set_next "validator" "ratelimit"
echo "Processing valid request:"
handler handle "auth" "token=valid&url=/api&data=payload"
echo "Processing invalid request:"
handler handle "auth" "url=/public" 89 How interviewers ask it “Show me state pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement state pattern with context and state transitions.
Context : current_state="ready"States : handle_state() { case $current_state in ready|processing|completed) ... }Transition : Change stateData : Track state data ShellCopy
#!/bin/bash
current_state="ready"
handle_state () {
case $current_state in
ready)
echo "Ready: Waiting for input"
current_state="processing"
;;
processing)
echo "Processing: Working on task"
current_state="completed"
;;
completed)
echo "Completed: Task finished"
current_state="ready"
;;
error)
echo "Error: Something went wrong"
current_state="ready"
;;
esac
}
declare -A state_data
stateful_context () {
local state=$1
case $state in
ready)
echo "Ready: Waiting for input"
state_data["last_state" ]="ready"
current_state="processing"
;;
processing)
echo "Processing: Working on task"
state_data["last_state" ]="processing"
current_state="completed"
;;
completed)
echo "Completed: Task finished"
state_data["last_state" ]="completed"
current_state="ready"
;;
error)
echo "Error: Something went wrong"
state_data["last_state" ]="error"
current_state="ready"
;;
esac
}
for i in {1..5}; do
echo "Step $i :"
handle_state
echo "State data: ${state_data["last_state"]:-none} "
done 90 How interviewers ask it “Show me proxy pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement proxy pattern for access control and lazy initialization.
Real subject : real_subject() { echo "RealSubject: Handling request"; }Proxy : proxy() { if [ -z "$cached_subject" ]; then ... }Logging : logging_proxy() { echo "Logging"; real_subject; }Auth : auth_proxy() { [ "$user" = "admin" ] && real_subject; } ShellCopy
#!/bin/bash
real_subject () {
echo "RealSubject: Handling request"
}
proxy () {
if [ -z "$cached_subject " ]; then
echo "Proxy: Creating real subject"
cached_subject="created"
fi
echo "Proxy: Using cached real subject"
real_subject
}
logging_proxy () {
echo "Logging: Request started"
real_subject
echo "Logging: Request completed"
}
auth_proxy () {
local user=$1
if [ "$user " = "admin" ]; then
echo "Auth: Access granted"
real_subject
else
echo "Auth: Access denied"
echo "Unauthorized"
fi
}
echo "$(proxy) "
echo "$(proxy) "
echo "$(logging_proxy) "
echo "$(auth_proxy admin) "
echo "$(auth_proxy guest) "
declare -A proxy_cache
caching_proxy () {
local key=$1
if [ -n "${proxy_cache[$key]} " ]; then
echo "Cache hit: ${proxy_cache[$key]} "
else
local result=$(real_subject)
proxy_cache[$key ]=$result
echo "Cache miss: $result "
fi
}91 How interviewers ask it “Show me flyweight pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement flyweight pattern for sharing objects.
Flyweight : flyweight() { echo "flyweight_$1"; }Factory : flyweight_cache[$shared_state]="flyweight_$shared_state"Operation : flyweight_operation() { echo "Shared: $flyweight, Unique: $unique_state"; }Share : Reuse instances ShellCopy
#!/bin/bash
declare -A flyweight_cache
flyweight () {
local shared_state=$1
if [ -z "${flyweight_cache[$shared_state]} " ]; then
flyweight_cache[$shared_state ]="flyweight_$shared_state "
fi
echo "${flyweight_cache[$shared_state]} "
}
flyweight_operation () {
local flyweight=$1
local unique_state=$2
echo "Shared: $flyweight , Unique: $unique_state "
}
fw1=$(flyweight "state1" )
fw2=$(flyweight "state1" )
fw3=$(flyweight "state2" )
echo "fw1 and fw2 are same: $([ "$fw1 " = "$fw2 " ] && echo "true" || echo "false" ) "
echo "fw1 and fw3 are same: $([ "$fw1 " = "$fw3 " ] && echo "true" || echo "false" ) "
flyweight_operation "$fw1 " "unique1"
flyweight_operation "$fw2 " "unique2"
flyweight_operation "$fw3 " "unique3"
echo "Number of flyweights: ${#flyweight_cache[@]} " 92 How interviewers ask it “Show me bridge pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement bridge pattern for separating abstraction from implementation.
Implementation : impl_a() { echo "ConcreteImplementationA: Operation"; }Abstraction : abstraction() { case $impl in A|B) ... }Extended : extended_abstraction() { ... }Alternative : alternative_abstraction() { ... } ShellCopy
#!/bin/bash
impl_a () {
echo "ConcreteImplementationA: Operation"
}
impl_b () {
echo "ConcreteImplementationB: Operation"
}
abstraction () {
local impl=$1
case $impl in
A) echo "Abstraction: Additional logic - $(impl_a) " ;;
B) echo "Abstraction: Additional logic - $(impl_b) " ;;
esac
}
extended_abstraction () {
local impl=$1
case $impl in
A) echo "Extended: More logic - $(impl_a) " ;;
B) echo "Extended: More logic - $(impl_b) " ;;
esac
}
alternative_abstraction () {
local impl=$1
case $impl in
A) echo "Alternative: Different logic - $(impl_a) " ;;
B) echo "Alternative: Different logic - $(impl_b) " ;;
esac
}
abstraction A
abstraction B
extended_abstraction A
extended_abstraction B
alternative_abstraction A
alternative_abstraction B93 How interviewers ask it “Show me adapter pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement adapter pattern for converting interfaces.
Target : target() { echo "Target: Request"; }Adaptee : adaptee() { echo "Adaptee: Specific Request"; }Adapter : adapter() { adaptee; }Logging : logging_adapter() { echo "Logging"; adaptee; } ShellCopy
#!/bin/bash
target () {
echo "Target: Request"
}
adaptee () {
echo "Adaptee: Specific Request"
}
adapter () {
adaptee
}
logging_adapter () {
echo "Adapter: Logging request"
adaptee
}
echo "$(target) "
echo "$(adapter) "
echo "$(logging_adapter) "
numeric_adapter () {
local input=$1
echo "$((input * 2) )"
}
string_adapter () {
local input=$1
echo "Converted: $input "
}
adapter_with_conversion () {
local type =$1
local data=$2
case $type in
numeric) numeric_adapter "$data " ;;
string) string_adapter "$data " ;;
esac
}94 How interviewers ask it “Show me facade pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement facade pattern for simplifying complex subsystems.
Subsystems : subsystem_a() { echo "SubsystemA: Operation"; }Facade : facade() { case $type in simple|complex) ... }Simplified : simplified_facade() { facade simple; }Config : facade_config() { case $config in minimal|standard|full) ... } ShellCopy
#!/bin/bash
subsystem_a () {
echo "SubsystemA: Operation"
}
subsystem_b () {
echo "SubsystemB: Operation"
}
subsystem_c () {
echo "SubsystemC: Operation"
}
facade () {
local type =$1
case $type in
simple)
subsystem_a
;;
complex)
subsystem_a
subsystem_b
subsystem_c
;;
esac
}
simplified_facade () {
facade simple
}
echo "Simple operation:"
facade simple
echo "Complex operation:"
facade complex
echo "Simplified facade:"
simplified_facade
facade_config () {
local config=$1
case $config in
minimal)
subsystem_a
;;
standard)
subsystem_a
subsystem_b
;;
full)
subsystem_a
subsystem_b
subsystem_c
;;
esac
}95 How interviewers ask it “Show me composite pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement composite pattern for tree structures.
Leaf : leaf() { echo "Leaf $1: Operation"; }Composite : composite() { echo "Composite $1: Operation"; for child in "{@:2}"; do eval "$child"; done; }Add : add_child() { ... }Count : count_leaves() { ... } ShellCopy
#!/bin/bash
leaf () {
local name=$1
echo "Leaf $name : Operation"
}
composite () {
local name=$1
shift
local children=("$@ " )
echo "Composite $name : Operation"
for child in "${children[@]} " ; do
eval "$child "
done
}
leaf1="leaf A"
leaf2="leaf B"
leaf3="leaf C"
leaf4="leaf D"
composite1="composite Comp1 $leaf1 $leaf2 "
composite2="composite Comp2 $leaf3 $composite1 "
root="composite Root $leaf4 $composite2 "
eval "$root "
count_leaves () {
local name=$1
shift
local children=("$@ " )
local count=0
for child in "${children[@]} " ; do
if [[ "$child " == leaf* ]]; then
count=$((count + 1 ))
else
local sub_count=$(eval "$child ; echo $?" )
count=$((count + sub_count))
fi
done
echo $count
}96 How interviewers ask it “Show me visitor pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement visitor pattern for adding operations to objects.
Visitor : concrete_visitor() { case $element in A*|B*) ... }Elements : element_a() { echo "ElementA: $data"; }Accept : concrete_visitor "$element"Counting : counting_visitor() { ... } ShellCopy
#!/bin/bash
element_a () {
local data=$1
echo "ElementA: $data "
}
element_b () {
local data=$1
echo "ElementB: $data "
}
concrete_visitor () {
local element=$1
case $element in
A*) element_a "${element#A:} " ;;
B*) element_b "${element#B:} " ;;
esac
}
counting_visitor () {
local element=$1
local count_a=$2
local count_b=$3
case $element in
A*)
count_a=$((count_a + 1 ))
echo "Visiting ElementA ($count_a ): ${element#A:} "
;;
B*)
count_b=$((count_b + 1 ))
echo "Visiting ElementB ($count_b ): ${element#B:} "
;;
esac
echo "$count_a :$count_b "
}
extended_visitor () {
local element=$1
case $element in
A*) echo "Extended: ${element#A:} (A)" ;;
B*) echo "Extended: ${element#B:} (B)" ;;
esac
}
elements=("A:Hello" "B:World" "A:Shell" "B:Visitor" )
echo "Using standard visitor:"
for el in "${elements[@]} " ; do
concrete_visitor "$el "
done
echo "Using counting visitor:"
count_a=0
count_b=0
for el in "${elements[@]} " ; do
result=$(counting_visitor "$el " "$count_a " "$count_b " )
count_a=$(echo "$result " | cut -d: -f1)
count_b=$(echo "$result " | cut -d: -f2)
done
echo "Counts: A=$count_a , B=$count_b "
echo "Using extended visitor:"
for el in "${elements[@]} " ; do
extended_visitor "$el "
done 97 How interviewers ask it “Show me iterator pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement iterator pattern for sequential access.
Iterator :create_iterator() { iterator_collection=("$@"); iterator_position=0; }Has next :has_next() { [ $iterator_position -lt ${#iterator_collection[@]} ]; }Next :next() { ... }Reverse :reverse_iterator() { for ((i=${#collection[@]}-1; i>=0; i--)); do ... } ShellCopy
#!/bin/bash
declare -a iterator_collection
iterator_position=0
create_iterator () {
local collection=("$@ " )
iterator_collection=("${collection[@]} " )
iterator_position=0
}
has_next () {
[ $iterator_position -lt ${#iterator_collection[@]} ]
}
next () {
if has_next; then
local item=${iterator_collection[$iterator_position]}
iterator_position=$((iterator_position + 1 ))
echo "$item "
fi
}
reverse_iterator () {
local collection=("$@ " )
for ((i=${#collection[@]} -1 ; i>=0 ; i--)); do
echo "${collection[$i]} "
done
}
filtered_iterator () {
local collection=("$@ " )
local predicate=$1
shift
for item in "$@ " ; do
if $predicate "$item " ; then
echo "$item "
fi
done
}
skip_iterator () {
local n=$1
shift
local collection=("$@ " )
for ((i=n; i<${#collection[@]} ; i++)); do
echo "${collection[$i]} "
done
}
collection=("A" "B" "C" "D" "E" )
create_iterator "${collection[@]} "
echo "Forward iteration:"
while has_next; do
echo "$(next) "
done
echo "Reverse iteration:"
reverse_iterator "${collection[@]} "
echo "Filtered iteration (length <= 1):"
filtered_iterator "test" "${collection[@]} "
echo "Skip 2:"
skip_iterator 2 "${collection[@]} " 98 How interviewers ask it “Show me template method pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement template method with customizable steps.
Template : template_method() { step1; step2; step3; }Default : default_template() { step1() { echo "Step 1"; }; ... }Logging : logging_template() { step1() { echo "Logging: Step 1"; }; ... }Data : data_template() { ... } ShellCopy
#!/bin/bash
template_method () {
step1
step2
step3
}
default_template () {
step1 () { echo "Step 1" ; }
step2 () { echo "Step 2" ; }
step3 () { echo "Step 3" ; }
template_method
}
logging_template () {
step1 () { echo "Logging: Step 1" ; }
step2 () { echo "Logging: Step 2" ; }
step3 () { echo "Logging: Step 3" ; }
template_method
}
data_template () {
local data=$1
step1 () { echo "Processing data: $data - Step 1" ; }
step2 () { echo "Processing data: $data - Step 2" ; }
step3 () { echo "Processing data: $data - Step 3" ; }
template_method
}
echo "Using default template:"
default_template
echo "Using logging template:"
logging_template
echo "Using data processing template:"
data_template "example" 99 How interviewers ask it “Show me builder pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement builder pattern for constructing complex objects.
Product : product_parts=()Builder : build_step_a() { product_parts+=("Part A"); }Director : build_minimal() { create_product; build_step_a; }Custom : build_custom() { for step in "$@"; do case $step in ... } ShellCopy
#!/bin/bash
declare -a product_parts
create_product () {
product_parts=()
}
add_part () {
product_parts+=("$1 " )
}
list_parts () {
echo "${product_parts[@]} "
}
builder () {
create_product
build_step_a () { add_part "Part A" ; }
build_step_b () { add_part "Part B" ; }
build_step_c () { add_part "Part C" ; }
get_result () { echo "${product_parts[@]} " ; }
}
director () {
build_minimal () {
create_product
build_step_a
}
build_full () {
create_product
build_step_a
build_step_b
build_step_c
}
build_custom () {
create_product
for step in "$@ " ; do
case $step in
A) build_step_a;;
B) build_step_b;;
C) build_step_c;;
esac
done
}
}
echo "Minimal product:"
build_minimal
list_parts
echo "Full product:"
build_full
list_parts
echo "Custom product:"
create_product
build_step_c
build_step_a
list_parts
echo "Director custom:"
build_custom C A B
list_parts100 How interviewers ask it “Show me prototype pattern in Shell Scripting — write it out and explain each step as you go.”
Coding Shell Scripting
Quick answer Implement prototype pattern for cloning objects.
Prototype : prototype() { echo "$1"; }Clone : clone_prototype() { echo "$1"; }Deep clone : deep_clone() { echo "$1"; }Mutable : set_mutable_data() { eval "$1='$2'"; } ShellCopy
#!/bin/bash
prototype () {
local data=$1
echo "$data "
}
clone_prototype () {
local data=$1
echo "$data "
}
deep_clone () {
local data=$1
echo "$data "
}
mutable_prototype () {
local data=$1
echo "$data "
}
set_mutable_data () {
local name=$1
local data=$2
eval "$name ='$data '"
}
get_mutable_data () {
local name=$1
eval "echo $$name "
}
original="Original"
copy=$(clone_prototype "$original " )
deep=$(deep_clone "$original " )
echo "Original: $original "
echo "Copy: $copy "
echo "Deep copy: $deep "
mutable="Mutable"
set_mutable_data mutable_data "Original data"
echo "Original data: $(get_mutable_data mutable_data) "
set_mutable_data mutable_data "Modified data"
echo "Modified data: $(get_mutable_data mutable_data) "
cloned_mutable=$(clone_prototype "$mutable " )
echo "Clone data: $cloned_mutable "
declare -A prototype_cache
cached_prototype () {
local data=$1
if [ -z "${prototype_cache[$data]} " ]; then
prototype_cache[$data ]="cached_$data "
fi
echo "${prototype_cache[$data]} "
}
Shell Scripting interview FAQ What is Shell Scripting? Shell scripting is a way to automate tasks in Unix and Linux operating systems by writing a sequence of shell commands in a script file that can be executed by a shell interpreter such as Bash.
What are the commonly used Shell scripting languages? Common Shell scripting languages include Bash, Bourne Shell (sh), Korn Shell (ksh), Z Shell (zsh), and C Shell (csh). Bash is the most widely used for Linux automation.
What is Bash in Shell scripting? Bash (Bourne Again Shell) is a popular Unix shell and scripting language used for command execution, automation, system administration, and DevOps tasks.
What are variables in Shell scripting? Variables in Shell scripting store data values such as strings, numbers, file paths, command outputs, and configuration information that can be reused throughout scripts.
What are loops in Shell scripting? Loops in Shell scripts allow repeated execution of commands. Common loops include for loop, while loop, and until loop, which are used for automation and batch processing.
What are functions in Shell scripting? Functions in Shell scripting are reusable blocks of commands that improve code organization, reduce duplication, and make scripts easier to maintain.
How does Shell scripting handle files? Shell scripts can create, read, write, copy, move, delete, search, and modify files using Linux commands such as cat, grep, sed, awk, cp, mv, and rm.
What is process management in Shell scripting? Process management in Shell scripting involves monitoring, starting, stopping, and controlling system processes using commands like ps, top, kill, and jobs.
How are regular expressions used in Shell scripting? Regular expressions are used in Shell scripts for pattern matching, searching, filtering text, validating input, and processing log files using tools like grep, sed, and awk.
How can I prepare for a Shell Scripting interview? Practice Linux commands, Bash syntax, variables, conditions, loops, functions, arrays, file handling, process management, regular expressions, debugging, and automation scripts used in real-world DevOps and system administration.