100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Bash

Common Shell Scripting Pitfalls

A field guide to the mistakes that silently break Bash scripts — unquoted variables, wrong test operators, subshell scoping, and error-handling gaps.

Interview PrepIntermediate11 min readJul 9, 2026
Analogies

Common Shell Scripting Pitfalls

Bash is forgiving syntax hides a surprising number of sharp edges. Scripts that work perfectly in casual testing can fail catastrophically in production when a filename contains a space, a variable happens to be empty, or a command in a pipeline silently fails. Because Bash rarely raises exceptions the way higher-level languages do, most of these pitfalls manifest as silent wrong behavior rather than loud crashes — which makes them dangerous and worth memorizing deliberately. This topic catalogs the mistakes that recur most often in real-world scripts, why they happen, and the idiomatic fix for each.

🏏

Cricket analogy: A batsman's technique looks fine in the nets but a yorker on off-stump in a real Boxing Day Test exposes the flaw instantly, just as a Bash script that runs fine in casual testing collapses in production on an edge case like a spaced filename.

Unquoted Variable Expansion

The single most common Bash bug is leaving variable expansions unquoted. When $var is not wrapped in double quotes, Bash performs word splitting on the characters in IFS (space, tab, newline by default) and then pathname expansion (globbing) on the result. A variable holding a filename like 'my report.txt' becomes two arguments, 'my' and 'report.txt', to whatever command receives it; a variable holding a glob-like pattern that happens to match files in the current directory expands into a list of filenames instead of staying literal. The fix is mechanical and absolute: always quote variable expansions unless you specifically want word splitting and globbing, which is rare and should be commented when intentional.

🏏

Cricket analogy: Failing to quote $var is like a scorer writing 'M S Dhoni' without commas on the scoresheet, so it gets read as three separate entries instead of one full name, just as an unquoted filename with a space splits into two arguments.

bash
# BROKEN: unquoted variable breaks on filenames with spaces
filename="my report.txt"
rm $filename          # tries to rm two files: 'my' and 'report.txt'

# CORRECT
rm "$filename"

# BROKEN: a loop that word-splits instead of iterating lines
for line in $(cat access.log); do
    echo "$line"       # splits on every space/tab/newline, not just newlines
done

# CORRECT: read line-by-line, preserving whitespace
while IFS= read -r line; do
    echo "$line"
done < access.log

rm -rf "$dir"/* is safer than rm -rf $dir/*, but neither protects you if $dir is accidentally empty or unset — the command silently becomes rm -rf /* semantics on the current directory tree. Always guard destructive commands with an explicit check ([[ -n "$dir" && -d "$dir" ]] || exit 1) before using a variable in an rm -rf, and consider set -u so an unset variable triggers an immediate error instead of expanding to an empty string.

Misusing Test Operators and Comparisons

Confusing string comparison with numeric comparison is a frequent source of bugs: = and == compare strings, while -eq, -ne, -lt, -gt, -le, -ge compare integers, and using the wrong one either produces a syntax error or, worse, silently wrong results (e.g., '10' -lt '9' correctly evaluates false numerically, but '10' < '9' as a string comparison would evaluate differently under lexicographic rules). Another classic mistake is using a single = inside [[ ]] versus (( )) inconsistently, or forgetting that [ ] (the POSIX test command) requires whitespace around every token, including brackets — [ $x -eq 1 ] works but [$x -eq 1] fails with a cryptic error because [ is actually a command name that needs a following space to be recognized as an argument.

🏏

Cricket analogy: Comparing '10' -lt '9' numerically correctly says false, but comparing them as strings is like ranking batting averages alphabetically instead of numerically, putting a .9 average ahead of a .10 average purely by lexicographic accident.

bash
# BROKEN: string comparison used where numeric was intended
if [ "$count" = "10" ]; then echo "ten"; fi   # works only for exact string '10'

# CORRECT: numeric comparison
if [ "$count" -eq 10 ]; then echo "ten"; fi

# BROKEN: missing space after [ — [ is a command, needs whitespace
#[$x -eq 1]     # syntax error: command not found

# CORRECT
if [ "$x" -eq 1 ]; then echo "one"; fi

# Bash-native arithmetic comparison, cleaner for numbers
if (( count == 10 )); then echo "ten"; fi

Pipelines, Subshells, and Lost Variable Scope

Each stage of a pipeline runs in its own subshell in Bash (with the notable exception of the last stage, depending on shopt lastpipe settings), which means variables assigned inside a command | while read ... loop vanish once the pipeline ends — a classic gotcha when trying to accumulate a count or build an array while reading piped input. Similarly, by default set -e does not abort a script when a command fails inside a pipeline unless that failing command is the last one, because only the last command's exit status determines the pipeline's overall status; set -o pipefail fixes this by making the pipeline's exit status reflect the first non-zero exit among all its stages.

🏏

Cricket analogy: Counting runs inside a command | while read loop is like a scorer who tallies boundaries only in their head during an over, then that tally vanishes once the over ends and the official scorebook resets — pipefail is the fix that captures the real total.

bash
# BROKEN: count is lost because the while loop runs in a subshell
count=0
cat access.log | while read -r line; do
    ((count++))
done
echo "$count"   # prints 0 — the increment happened in a subshell

# CORRECT: avoid the pipeline subshell using process substitution
count=0
while read -r line; do
    ((count++))
done < <(cat access.log)
echo "$count"   # prints the real count

# Ensure pipeline failures aren't masked
set -euo pipefail
grep "ERROR" app.log | sort | uniq -c   # now fails loudly if grep or sort errors

The classic 'Useless Use of Cat' (UUOC) is a stylistic pitfall rather than a correctness bug, but it's worth knowing: cat file | grep pattern spawns an unnecessary process when grep pattern file does the same job directly. It matters more in tight loops or when processing huge files repeatedly, where the extra fork/exec and pipe buffering add measurable overhead.

Silent Failures and Missing Error Handling

Scripts without set -e (or with -e disabled by a pipeline/conditional context) continue executing after a failed command, often cascading into far more confusing errors downstream — a failed cd followed by destructive operations on the wrong directory is a textbook disaster scenario. Forgetting to check the exit status of critical commands, ignoring $?, and not distinguishing between a command that legitimately produces no output versus one that failed outright are all variations of the same root issue: treating shell scripts as if they had exception handling by default, when in fact every command's success must be checked explicitly or the script must opt into strict-mode behavior.

🏏

Cricket analogy: Failing to check cd's exit status before deleting files is like a fielder charging in to take a catch without confirming they're standing in the right position, then colliding disastrously with a teammate — the same cascading-error pattern as skipping set -e.

bash
# DANGEROUS: if cd fails, subsequent commands run in the wrong directory
cd /some/build/dir
rm -rf ./*

# SAFER: fail loudly if cd doesn't succeed
cd /some/build/dir || { echo "cd failed, aborting" >&2; exit 1; }
rm -rf ./*

# Recommended defensive header for most production scripts
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
  • Always quote variable expansions ("$var") to prevent word splitting and unwanted globbing — the single most common Bash bug.
  • Use -eq/-ne/-lt/-gt for numeric comparisons and = / == for string comparisons; mixing them causes silent logic errors.
  • Variables set inside a piped while-read loop are lost when the pipeline ends, because each stage runs in a subshell; use process substitution (< <(...)) to avoid this.
  • set -o pipefail is required alongside set -e for pipeline failures to actually abort the script, since only the last command's exit status is checked by default.
  • Guard destructive commands (especially rm -rf on a variable path) with explicit checks that the variable is set and non-empty.
  • Always check the exit status of critical commands like cd before proceeding with destructive operations — cd dir || exit 1 is a minimal, essential safeguard.

Practice what you learned

Was this page helpful?

Topics covered

#Bash#LinuxShellScriptingStudyNotes#DevOps#CommonShellScriptingPitfalls#Common#Shell#Scripting#Pitfalls#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse