当前位置: 首页 > news >正文

[Bash] bash scripting common pitfalls

 

Absolutely — Bash feels strange because it blends shell commands, programming constructs, and POSIX quirks. If you come from Python, it’s easy to trip over hidden pitfalls. Here’s a thorough list, organized by category:


1. Quoting Issues

  • Unquoted variables can lead to word splitting and glob expansion:

name="John Doe"
echo $name       # BAD: expands to two words
echo "$name"     # GOOD: preserves spaces
  • Forgetting quotes can break tests or loops:

if [ $a -eq 5 ]; then ...  # ERROR if $a is empty
if [ "$a" -eq 5 ]; then ...  # SAFE
  • Using single quotes ' prevents variable expansion:

echo '$HOME'  # prints literally $HOME
echo "$HOME"  # prints /home/user

2. Conditional Confusion

  • Mixing [ ], [[ ]], (( )), and () incorrectly:

if (("$a" < 5)); then ...  # BAD: use ((a < 5))
if [ $a < 5 ]; then ...    # BAD: < is string comparison in [ ]
  • Confusing string vs numeric comparisons:

[ "$a" -lt 5 ]   # numeric
[ "$a" \< "5" ]  # string (note escaped <)
  • Assuming if [ "$a" ] checks for number. It actually checks non-empty string.


3. Exit Status Pitfalls

  • Bash uses exit codes: 0 = success, non-zero = failure. Python uses True/False.

if grep foo file.txt; thenecho "Found"
fi
  • Many commands return unexpected codes; e.g., test returns 1 for false, 0 for true.

  • Forgetting set -e or error handling can silently ignore failures.


4. Loop and Variable Scope Issues

  • Variables are global by default; subshells create separate scopes:

( a=5 )
echo $a  # empty: set in subshell
  • Iterating over unquoted expansions can split on spaces unexpectedly:

files="file 1.txt file2.txt"
for f in $files; do echo "$f"; done
# BAD: splits "file 1.txt" into "file" and "1.txt"
for f in "$files"; do echo "$f"; done  # prints entire string
  • Use arrays to handle multiple items safely.


5. Command Substitution Oddities

  • $(command) is preferred over backticks `command`.

  • Spaces and newlines in output can break things:

files=$(ls)
# BAD if filenames have spaces
  • Better: use arrays:

mapfile -t files < <(ls)

6. File and Path Problems

  • Forgetting -e, -f, -d in tests leads to errors:

if [ -f "$file" ]; then echo "File exists"; fi
  • Globbing (*, ?) can expand unexpectedly; always quote or shopt -s nullglob.


7. Arithmetic Gotchas

  • (( ... )) handles integers only. No floating point:

a=3.14
((a > 3))  # ERROR
  • Bash string variables are always strings; using -eq on non-numeric values fails.


8. Function Syntax Confusion

  • Bash allows two forms:

myfunc() { echo "hi"; }
function myfunc { echo "hi"; }  # also valid in Bash
  • return only sets exit code, not value. Use echo for output.


9. Quirky String Manipulation

  • ${var#pattern}, ${var%pattern} — powerful, but not obvious.

  • ${var:-default} vs ${var:=default} — subtle difference between default for expansion and assignment.


10. Portability Pitfalls

  • Scripts using [[ ]], (( )), or Bash-specific function keyword are not POSIX compliant.

  • Some commands (e.g., read -p) differ between Bash, Dash, and macOS.


11. Miscellaneous Gotchas

  • && / || short-circuit can silently skip commands.

  • Forgetting #!/bin/bash vs /bin/sh changes behavior.

  • I/O redirection mistakes: > vs >>, overwriting files unintentionally.

  • Using expr vs (( )) vs $(( )) — inconsistent arithmetic can confuse beginners.


Advice for Pythonistas:

  1. Quote everything unless you deliberately want word splitting.

  2. Use [[ ]] for string/numeric conditions in Bash scripts.

  3. Use arrays to store multiple items safely.

  4. Check exit codes carefully; if tests commands, not expressions.

  5. Enable strict mode at the top of scripts:

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
  • -e → exit on error

  • -u → error on undefined variables

  • -o pipefail → pipe errors propagate


If you want, I can make a “cheat sheet of safe Bash practices for Python programmers” — basically a guide to avoid 90% of these pitfalls. It’s a huge time saver.

Do you want me to do that?

http://www.hskmm.com/?act=detail&tid=36228

相关文章:

  • [Bash]让人头晕的if条件
  • 鸭子类型(Duck Typing)中的“类型”,指的是什么的类型?为什么很多人认为“Python 没有真正实现多态”?多态的核心目的是什么?鸭子类型如何实现多态?
  • tryhackme-预安全-windows基础-windows 基础知识1-16
  • YOLO11深度学习的遥感视角地面房屋建筑检测分割与分析系统 - MKT
  • 鸭子类型(Duck Typing)中的“类型”,指的是什么的类型?为什么很多人认为“Python 没有真正实现多态”
  • OAK-D-SR近红外相机 - MKT
  • 图像分割 Segment Anything(1-2)第二代 - MKT
  • 对比c++中的多态和python的多态
  • 结对项目-自动生成小学四则运算题目命令行程序
  • tryhackme-预安全-linux 基础-Linux 基础知识(第二部分)-14
  • tryhackme-预安全-linux 基础-Linux 基础知识(第一部分)-13
  • 我测试了七个主流后端框架的性能-结果让我重新思考了技术选型
  • tryhackme-预安全-网络如何工作-总结-12
  • 目标检测 Grounding DINO 用语言指定要检测的目标 - MKT
  • 图像分割 Segment Anything(3)分割2D到3D点云分割 rgb-d相机 - MKT
  • 图像分割 3D-Box-Segment-Anything(3)分割2D到3D点云分割 rgb相机 - MKT
  • 图像分割 Segment Anything(3)分割2D到3D点云分割 rgb相机 - MKT
  • Python 包管理工具推荐:uv
  • 3D框预测 VoxelNeXt - MKT
  • 【神器】如何查看api域名内容
  • 高级程序语言第二次作业
  • 【ESP32-LLM项目】计算音频信号RMS值的函数
  • Linux消息队列如何查看与排查问题?
  • CF2007B Index and Maximum Value
  • 2022 ICPC Jinan DG and 2022 ICPC Nanjing
  • 图像分割 sam1 - MKT
  • SDL-1
  • CF1206B Make Product Equal One
  • 软件工程第三次作业----结对项目
  • 关于莫比乌斯函数的应用1