Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

“Invest in yourself — your confidence is always worth it.”

Explore Cosmetic Hospitals

Start your journey today — compare options in one place.

Shell and Bash Interview Questions: Practical Answers, Commands, and Script Patterns

Originally published on 2010-04-16; fully revised and updated.

This guide converts a legacy shell interview question list into a structured Bash reference for DevOps engineers. It covers essential commands, process control, conditionals and loops, text processing, and safer scripting practices you can use in both interviews and real operations work.

Shell programming interview questions

Core shell commands interviewers ask first

These are foundational commands that appear frequently in shell interviews. Knowing both the command and its practical context matters more than memorizing one-liners.

Interview promptCommandWhat it does
Find your current shellecho $SHELLPrints your login shell path
Show current date/timedateDisplays system date and time
List logged-in userswhoShows active logins
Show current directorypwdPrints working directory
Show current usernamewhoamiPrints effective user
Count lines/words/byteswc file.txtBasic file metrics
Search text in filegrep "text" file.txtMatches lines containing text
Search recursively in directorygrep -R "text" /pathRecursive search across files
Delete a filerm file.txtRemoves a file
Delete recursivelyrm -rf /pathForce-removes directory tree (dangerous)
echo "$SHELL"
date
who
pwd
whoami
wc app.log
grep "ERROR" app.log
grep -R "ERROR" /var/log/myappCode language: PHP (php)

Process and job control essentials

Process control questions often test whether you understand inspection first, termination second. Interviewers usually expect safe handling of PIDs and exit status checks.

TaskCommandNotes
List running processesps or ps -efOutput format depends on platform/options
Find process by patternpgrep -f nameUseful before kill
Terminate gracefullykill -TERM PIDPreferred first signal
Force terminatekill -KILL PIDUse only when graceful stop fails
Run in backgroundcommand &Starts job asynchronously
Current shell PIDecho $$PID of current shell process
Last background PIDecho $!PID of most recent background job
Last command statusecho $?0 usually indicates success
Signal process groupkill 0Can affect multiple processes in current process group
pid="$(pgrep -f my-service)"
if [ -n "$pid" ]; then
  kill -TERM "$pid"
  sleep 2
  ps -p "$pid"
fiCode language: JavaScript (javascript)

Special shell parameters you should remember

ParameterMeaning
$0Script name
$1, $2…Positional arguments
$#Number of positional arguments
$*All positional args (single word context)
$@All positional args (preserves argument boundaries when quoted)
$?Exit status of last command
$$Current shell PID
$!PID of last background command

Conditionals, tests, and loops in Bash

Interviewers commonly ask for basic control flow syntax and test operators. Be ready to combine numeric, string, and file checks cleanly.

if/elif with numeric, string, and file tests

count=12
file="/tmp/report.txt"

if [ "$count" -gt 10 ] && [ -f "$file" ]; then
  echo "Large run and report exists"
elif [ -z "$file" ]; then
  echo "No report file specified"
else
  echo "Conditions not met"
fiCode language: PHP (php)

for, while, and case patterns

for env in dev stage prod; do
  echo "Deploying to $env"
done

i=1
while [ "$i" -le 3 ]; do
  echo "Attempt $i"
  i=$((i + 1))
done

read -r action
case "$action" in
  status) ps -ef ;;
  users) who ;;
  now) date ;;
  *) echo "Invalid option" ;;
esacCode language: PHP (php)

Text processing one-liners frequently asked in interviews

TaskCommandNotes
List only empty linesgrep '^$' file.txtMatches blank lines
Remove blank linesgrep -v '^$' file.txt or sed '/^$/d' file.txtTwo common approaches
Extract character positions 10-20cut -c 10-20 file.txtCharacter-based slicing
Print line 25sed -n '25p' file.txtDirect and compact
Replace n with xyzsed 's/n/xyz/g' file.txtGlobal replacement per line
List users from passwd filecut -d: -f1 /etc/passwdUsername field extraction
grep '^$' file.txt
grep -v '^$' file.txt > no_blanks.txt
sed '/^$/d' file.txt > no_blanks_sed.txt
cut -c 10-20 file.txt
sed -n '25p' file.txt
sed 's/n/xyz/g' file.txt > new_file.txtCode language: JavaScript (javascript)

Legacy reference preserved from the original post: Shell script to read file line by line.

Parsing options with getopts

getopts is a standard way to parse short options like -n 15 -x 20 in shell scripts.

#!/usr/bin/env bash
num=""
xval=""

while getopts "n:x:" opt; do
  case "$opt" in
    n) num="$OPTARG" ;;
    x) xval="$OPTARG" ;;
    *) echo "Usage: $0 -n number -x value"; exit 1 ;;
  esac
done

echo "n=$num x=$xval"Code language: PHP (php)

Quick conceptual answers from common shell interviews

  • What is a named pipe? A FIFO special file used for inter-process communication.
  • What does cmd1 && cmd2 mean? Run cmd2 only if cmd1 succeeds.
  • What does cmd1 || cmd2 mean? Run cmd2 only if cmd1 fails.
  • Exported vs non-exported variable: Exported variables are inherited by child processes; non-exported variables remain in the current shell.
  • Open a read-only file in vi: vi -R filename.
  • Schedule a 4:00 AM daily job: use a cron entry.
crontab -e
0 4 * * * /usr/local/bin/backup.sh

tar -zxvf archive.tar.gz
uname -m
find . -type f -perm 0655 -exec chmod 0755 {} \;Code language: JavaScript (javascript)

Typical script execution workflow

flowchart TD
    A[Run script with arguments] --> B[getopts parses options]
    B --> C[Validate required inputs]
    C --> D{Inputs valid}
    D -- no --> E[Print usage and exit 1]
    D -- yes --> F[Run main commands]
    F --> G[Capture exit code]
    G --> H{Exit code is 0}
    H -- yes --> I[Report success]
    H -- no --> J[Report failure and exit nonzero]

Best practices and common pitfalls

  • Prefer safe defaults: inspect with ps/pgrep before using kill.
  • Use quoted variables in scripts to avoid word-splitting bugs.
  • Treat rm -rf and kill -KILL as last-resort operations.
  • Check exit codes ($?) and return nonzero status on failures.
  • Use grep -R or find deliberately instead of broad globs like * in large directories.
  • Remember that command options and output can vary across Linux/Unix distributions and shells.

If you can explain these commands and patterns clearly, you will handle most shell/Bash interview rounds with confidence.

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

TFS Interview Questions and Answers: Practical DevOps Guide

A structured, interview-focused guide to Team Foundation Server (TFS), including TFVC vs Git, build and reporting topics, and practical command examples. Use it to prepare concise, technically strong answers for common TFS interview scenarios.

Read More

Chef Interview Q&A (Part 2): Resources, Run-Lists, Bootstrap, and Test Kitchen

A practical rewrite of classic Chef interview questions, focused on how Chef resources converge, how run-lists drive node configuration, and how to test cookbooks safely. Includes command examples, workflow diagrams, and comparison tables.

Read More

Chef Interview Questions, Explained: Resources, Run-Lists, Bootstrapping, and Test Kitchen

This updated guide converts classic Chef interview Q&A into a practical reference for real infrastructure work. It covers core concepts, execution order, bootstrap flow, key knife commands, and Test Kitchen testing patterns.

Read More

SVN Interview Questions and Answers: Trunk, Branch, Tag, Update, Commit, Patch, Backup, and Authentication

A practical, interview-focused guide to Subversion (SVN) concepts and commands. Learn how to explain trunk/branch/tag, update vs commit, conflict handling, patching, backup/restore, and auth setup with confidence.

Read More

Jenkins Interview Questions, Answered: CI, APIs, Installation, Backups, and Essential Plugins

This revised guide turns common Jenkins interview prompts into practical answers you can explain with confidence. It covers CI fundamentals, API usage, setup on Ubuntu and RHEL-like systems, backup strategy, and key plugins.

Read More

Git, GitHub, and GitLab Interview Questions: Practical Answers and Command Guide

A practical interview-prep guide covering core Git concepts, essential commands, and common GitHub/GitLab questions. Includes workflow diagrams, comparisons, and troubleshooting checklists.

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x