Kritim Yantra
May 04, 2025
If you're preparing for a Linux admin, DevOps, or automation role, shell scripting is often a key skill tested in interviews. This blog covers common shell scripting interview questions with simple, clear answers to help you prepare confidently.
Answer:
A shell script is a text file containing a series of Linux commands that are executed sequentially. It helps automate repetitive tasks.
Example:
#!/bin/bash
echo "Hello, World!"
#!
) line?Answer:
The shebang (#!
) tells the system which interpreter (like /bin/bash
) should execute the script.
Example:
#!/bin/bash # Uses Bash shell
#!/bin/sh # Uses the default shell
Answer:
Use chmod +x
to give execute permission:
chmod +x script.sh
./script.sh # Run the script
Answer:
Use #
for single-line comments:
# This is a comment
echo "Hello" # Inline comment
Answer:
name="Alice" # Define
echo "Hello, $name" # Use (with $)
Answer:
Use read
:
echo "Enter your name:"
read username
echo "Hello, $username!"
$@
and $*
?Answer:
$@
→ Treats each argument as a separate word. $*
→ Treats all arguments as a single string.Example:
./script.sh arg1 arg2
# $@ = "arg1" "arg2"
# $* = "arg1 arg2"
if-else
statement?Answer:
if [ condition ]; then
# Code
else
# Code
fi
Example:
if [ -f "file.txt" ]; then
echo "File exists!"
else
echo "File not found."
fi
for
loop?Answer:
for i in 1 2 3; do
echo "Number: $i"
done
Example (Loop through files):
for file in *.txt; do
echo "Processing $file"
done
while
loop?Answer:
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
Answer:
function greet() {
echo "Hello, $1!"
}
greet "Alice" # Output: Hello, Alice!
Answer:
$0
→ Script name $1
, $2
→ First, second argument $#
→ Total argumentsExample:
echo "First argument: $1"
echo "Total arguments: $#"
Answer:
Use -f
:
if [ -f "file.txt" ]; then
echo "File exists!"
fi
Answer:
Use grep
:
grep "error" logfile.txt
Answer:
Use sed
:
sed -i 's/old/new/g' file.txt
Answer:
Use set -e
:
#!/bin/bash
set -e # Exit on error
rm non_existent_file # Script stops if this fails
Answer:
Run with -x
for debugging:
bash -x script.sh
Answer:
#!/bin/bash
find /var/log -name "*.log" -mtime +30 -delete
Answer:
#!/bin/bash
threshold=90
usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if [ $usage -gt $threshold ]; then
echo "Warning: Disk space low!"
fi
Answer:
✔ Use comments (#
) to explain code.
✔ Quote variables ("$var"
) to avoid errors.
✔ Use [[ ]]
instead of [ ]
for safer comparisons.
✔ Test scripts in small steps.
0
= success, non-zero
= failure). Shell scripting is a must-know skill for Linux and DevOps roles. These interview questions and answers cover basics to real-world scenarios.
🚀 Keep practicing, and you’ll ace your interview!
Got more questions? Ask in the comments! 💬🐧
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google