功能说明
示例从第一个位置参数取得文件路径,依次用 -f、-d、-e 判断它是普通文件、目录还是其他已存在类型;随后演示数值比较、字符串非空与前缀匹配、读写权限组合判断,以及用算术三元表达式求奇偶标志。
关键代码
file="${1:-}"在set -u下安全读取可选参数,未传参时得到空字符串。if [[ -f "$file" ]]使用[[ ]]做文件测试,elif继续判断目录和存在性,else处理不存在的情况。(( num > 50 ))与(( num == 42 ))用于整数比较,变量名在算术上下文中无需$。[[ -n "$str" && "$str" == h* ]]同时检查非空和 glob 前缀匹配,&&具有短路效果。[[ -r "$file" && -w "$file" ]]组合权限测试;result=$(( num % 2 == 0 ? 1 : 0 ))用三元表达式得到 1 或 0。
使用注意
[[ ]] 中的变量应加引号,避免空值或空格引发语法问题;== 右侧的 h* 是模式而非普通字符串。[ ] 与 [[ ]] 行为不同,脚本统一使用后者。文件测试对不存在的路径返回假,-r 与 -w 反映当前用户的访问权限,换用其他用户运行可能得到不同结果。
验证方式
分别以存在的文件、目录和不存在的路径作为参数运行,确认三类分支输出正确;不传参数时应输出 Does not exist:。数值部分应打印 The answer to everything,字符串部分应命中 h 前缀分支,奇偶结果为 1。
代码示例
#!/usr/bin/env bash
set -euo pipefail
file="${1:-}"
num=42
# File tests
if [[ -f "$file" ]]; then
echo "Regular file: $file"
elif [[ -d "$file" ]]; then
echo "Directory: $file"
elif [[ -e "$file" ]]; then
echo "Exists but unknown type"
else
echo "Does not exist: $file"
fi
# Numeric comparisons
if (( num > 50 )); then
echo "Greater than 50"
elif (( num == 42 )); then
echo "The answer to everything"
else
echo "Less than 42"
fi
# String tests
str="hello"
if [[ -n "$str" && "$str" == h* ]]; then
echo "Non-empty string starting with h"
fi
# Logical operators
if [[ -r "$file" && -w "$file" ]]; then
echo "File is readable and writable"
fi
# Ternary-like assignment
result=$(( num % 2 == 0 ? 1 : 0 ))
echo "Is even: $result"