插件窝 干货文章 第二节:Bash编程易犯的错误

第二节:Bash编程易犯的错误

Bash 错误 示例 问题 740    来源:    2025-05-19

Bash编程易犯的错误

1. 引号使用不当

错误示例:

echo $USER's home directory is $HOME

问题: - 单引号会阻止变量展开 - 字符串拼接方式不正确

正确做法:

echo "$USER's home directory is $HOME"
# 或
echo "${USER}'s home directory is ${HOME}"

2. 未加引号的变量

错误示例:

if [ $var = "test" ]; then

问题: - 当$var为空时,表达式会变成[ = "test" ],导致语法错误

正确做法:

if [ "$var" = "test" ]; then

3. 数字比较使用错误运算符

错误示例:

if [ $a > $b ]; then

问题: - >[ ]中是重定向符号,不是比较运算符

正确做法:

if [ $a -gt $b ]; then
# 或使用双括号
if (( a > b )); then

4. 循环中的管道问题

错误示例:

find . -type f | while read file; do
    count=$((count+1))
done
echo "Total files: $count"

问题: - 管道会创建子shell,变量修改不会影响父shell

正确做法:

count=0
while read file; do
    count=$((count+1))
done < <(find . -type f)
echo "Total files: $count"

5. 命令替换中的换行符问题

错误示例:

files=$(ls)
for file in $files; do
    echo "$file"
done

问题: - 文件名中的空格和换行符会导致解析错误

正确做法:

while IFS= read -r -d '' file; do
    echo "$file"
done < <(find . -type f -print0)

6. 测试文件存在性的问题

错误示例:

if [ -f $file ]; then

问题: - 当$file包含空格或特殊字符时会出错 - 当$file为空时测试会通过

正确做法:

if [ -n "$file" ] && [ -f "$file" ]; then

7. 使用反引号而非$()

错误示例:

output=`command`

问题: - 反引号难以嵌套,可读性差

正确做法:

output=$(command)

8. 未处理命令返回值

错误示例:

rm important_file
echo "File removed"

问题: - 如果删除失败,脚本会继续执行而不报错

正确做法:

if ! rm important_file; then
    echo "Failed to remove file" >&2
    exit 1
fi
echo "File removed"

9. 使用==进行字符串比较

错误示例:

if [ "$str" == "test" ]; then

问题: - ==不是POSIX标准,在某些shell中可能不支持

正确做法:

if [ "$str" = "test" ]; then

10. cd未检查返回值

错误示例:

cd /nonexistent/directory

问题: - 如果目录不存在,后续命令会在错误位置执行

正确做法:

if ! cd /nonexistent/directory; then
    echo "Failed to change directory" >&2
    exit 1
fi

最佳实践建议

  1. 始终引用变量:除非有特殊原因,否则总是用双引号包裹变量
  2. 使用set -euo pipefail:在脚本开头添加这些选项可以捕获许多常见错误
  3. 检查命令返回值:特别是对关键操作
  4. 使用shellcheck:这是一个静态分析工具,可以检测许多bash脚本问题
  5. 避免解析ls输出:使用find或glob模式替代
  6. 使用数组处理多个元素:特别是当元素可能包含空格时
#!/bin/bash
set -euo pipefail

# 你的脚本内容