[Bash] bash scripting common pitfalls

news/2025/10/22 5:26:10/文章来源:https://www.cnblogs.com/profesor/p/19156792

 

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.mzph.cn/news/942833.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[Bash]让人头晕的if条件

来自chatgptAh, yes — Bash’s conditional syntax is notoriously confusing because it has several different “types” of tests, and each has subtle differences. Let’s break it down carefully. You were …

鸭子类型(Duck Typing)中的“类型”,指的是什么的类型?为什么很多人认为“Python 没有真正实现多态”?多态的核心目的是什么?鸭子类型如何实现多态?

鸭子类型(Duck Typing)中的“类型”,指的是什么的类型? 鸭子类型(Duck Typing)中的“类型”,指的是“具备特定行为的对象的类型”——它不是传统意义上“由类定义的类型”(如 int、str 或自定义类),而是“由…

tryhackme-预安全-windows基础-windows 基础知识1-16

tryhackme-Pre Security-Windows Fundamentals -Windows Fundamentals 1 房间地址:https://tryhackme.com/room/windowsfundamentals1xbx 这是网络安全入门的基础模块的计算机科学基础知识:Windows Fundamentals 1(…

YOLO11深度学习的遥感视角地面房屋建筑检测分割与分析系统 - MKT

YOLO11深度学习的遥感视角地面房屋建筑检测分割与分析系统 https://blog.csdn.net/qq_42589613/article/details/146162941一、软件核心功能介绍及效果演示软件主要功能1. 可进行遥感视角地面房屋建筑检测分割,分割一…

鸭子类型(Duck Typing)中的“类型”,指的是什么的类型?为什么很多人认为“Python 没有真正实现多态”

鸭子类型(Duck Typing)中的“类型”,指的是“具备特定行为的对象的类型”——它不是传统意义上“由类定义的类型”(如 int、str 或自定义类),而是“由对象具备的方法/属性(行为)所定义的逻辑类型”。简单说:“…

图像分割 Segment Anything(1-2)第二代 - MKT

图像分割 Segment Anything(1-2)第二代 大模型 8秒 1800*1200 压缩一半# 使用前需要先安装 SAM 2。代码需要python>=3.10、 以及torch>=2.5.1和。请按照此处的torchvision>=0.20.1说明安装 PyTorch 和 Tor…

对比c++中的多态和python的多态

C++ 和 Python 中的“多态”都围绕“同一接口、不同实现”的核心思想,但由于语言特性(静态类型 vs 动态类型)的差异,两者在实现方式、约束性、灵活性上有显著区别。以下从核心机制、实现条件、使用场景等维度对比:…

OAK-D-SR近红外相机 - MKT

OAK-D-SR近红外相机 https://www.oakchina.cn/2024/08/13/%E5%85%B7%E6%9C%89-sam2-%E5%88%86%E6%AE%B5%E7%9A%84-ndvi-%E6%97%A0%E4%BA%BA%E6%9C%BA/

结对项目-自动生成小学四则运算题目命令行程序

(一)这个作业属于哪个课程 https://edu.cnblogs.com/campus/gdgy/Class34Grade23ComputerScience这个作业要求在哪里 https://edu.cnblogs.com/campus/gdgy/Class34Grade23ComputerScience/homework/13479这个作业的…

tryhackme-预安全-linux 基础-Linux 基础知识(第二部分)-14

tryhackme-Pre Security-Linux Fundamentals-Linux Fundamentals Part 2 房间地址:https://tryhackme.com/room/linuxfundamentalspart2 这是网络安全入门的基础模块的计算机科学基础知识:Linux Fundamentals Part 2…

tryhackme-预安全-linux 基础-Linux 基础知识(第一部分)-13

tryhackme-Pre Security-Linux Fundamentals-Linux Fundamentals Part 1 房间地址:https://tryhackme.com/room/linuxfundamentalspart1 这是网络安全入门的基础模块的计算机科学基础知识:Linux Fundamentals Part 1…

我测试了七个主流后端框架的性能-结果让我重新思考了技术选型

说实话,在开始这次测试之前,我从来没想过性能差异会这么大。作为一个大三的计算机专业学生,我一直觉得框架选择主要看功能和生态,性能嘛,差不多就行了。直到上个月,我们实验室的一个项目因为并发量上来后服务器频…

tryhackme-预安全-网络如何工作-总结-12

tryhackme-Pre Security-How The Web Works-Putting it all together 房间地址:https://tryhackme.com/room/puttingitalltogether 这是网络安全入门的基础模块的计算机科学基础知识:Putting it all together(总结)…

目标检测 Grounding DINO 用语言指定要检测的目标 - MKT

目标检测 Grounding DINO 用语言指定要检测的目标https://github.com/IDEA-Research/GroundingDINO

图像分割 3D-Box-Segment-Anything(3)分割2D到3D点云分割 rgb相机 - MKT

图像分割 3D-Box-Segment-Anything(3)分割2D到3D点云分割 rgb相机https://github.com/dvlab-research/3D-Box-Segment-AnythingVoxelNeXt (CVPR 2023) [论文] [代码]用于 3D 对象检测和跟踪的完全稀疏 VoxelNet。

图像分割 Segment Anything(3)分割2D到3D点云分割 rgb-d相机 - MKT

图像分割 Segment Anything(3)分割2D到3D点云分割 rgb-d相机 https://github.com/Pointcept/SegmentAnything3D

Python 包管理工具推荐:uv

目录简介核心特性安装 uvLinux / macOS / WSL WindowsPython 版本管理安装和管理 Python 版本项目环境管理为新项目创建环境 为已有代码创建环境依赖管理添加依赖 从已有依赖文件迁移从 requirements.txt 导入 使用已有…

图像分割 Segment Anything(3)分割2D到3D点云分割 rgb相机 - MKT

图像分割 Segment Anything(3)分割2D到3D点云分割 rgb相机 https://github.com/Pointcept/SegmentAnything3D

3D框预测 VoxelNeXt - MKT

3D框预测 VoxelNeXthttps://github.com/dvlab-research/VoxelNeXt

【神器】如何查看api域名内容

查看API域名内容的方法有多种,包括使用在线工具、浏览器插件、命令行工具等。通过这些工具,你可以轻松获取API的响应数据、测试API的可用性、检查API的性能。 其中,常见的方法包括使用Postman、cURL命令行工具、浏览…