错误示例:
echo $USER's home directory is $HOME
问题: - 单引号会阻止变量展开 - 字符串拼接方式不正确
正确做法:
echo "$USER's home directory is $HOME"
# 或
echo "${USER}'s home directory is ${HOME}"
错误示例:
if [ $var = "test" ]; then
问题:
- 当$var
为空时,表达式会变成[ = "test" ]
,导致语法错误
正确做法:
if [ "$var" = "test" ]; then
错误示例:
if [ $a > $b ]; then
问题:
- >
在[ ]
中是重定向符号,不是比较运算符
正确做法:
if [ $a -gt $b ]; then
# 或使用双括号
if (( a > b )); then
错误示例:
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"
错误示例:
files=$(ls)
for file in $files; do
echo "$file"
done
问题: - 文件名中的空格和换行符会导致解析错误
正确做法:
while IFS= read -r -d '' file; do
echo "$file"
done < <(find . -type f -print0)
错误示例:
if [ -f $file ]; then
问题:
- 当$file
包含空格或特殊字符时会出错
- 当$file
为空时测试会通过
正确做法:
if [ -n "$file" ] && [ -f "$file" ]; then
错误示例:
output=`command`
问题: - 反引号难以嵌套,可读性差
正确做法:
output=$(command)
错误示例:
rm important_file
echo "File removed"
问题: - 如果删除失败,脚本会继续执行而不报错
正确做法:
if ! rm important_file; then
echo "Failed to remove file" >&2
exit 1
fi
echo "File removed"
错误示例:
if [ "$str" == "test" ]; then
问题:
- ==
不是POSIX标准,在某些shell中可能不支持
正确做法:
if [ "$str" = "test" ]; then
错误示例:
cd /nonexistent/directory
问题: - 如果目录不存在,后续命令会在错误位置执行
正确做法:
if ! cd /nonexistent/directory; then
echo "Failed to change directory" >&2
exit 1
fi
#!/bin/bash
set -euo pipefail
# 你的脚本内容