echo "$FILE does not exist or is not a regular file"
fi
# 字符串比较
NAME="John"
if [ "$NAME" = "John" ]; then
echo "Hello, John!"
else
echo "You're not John"
fi
# 逻辑运算
if [ -f "/etc/passwd" ] && [ -r "/etc/passwd" ]; then
echo "/etc/passwd exists and is readable"
fi
复制代码
• 循环结构
“`bash
#!/bin/bash
# for循环
echo “Counting to 5:”
for i in {1..5}; do
echo "Number: $i"
复制代码
done
# C风格的for循环
echo “Counting to 5 again:”
for ((i=1; i<=5; i++)); do
echo "Number: $i"
复制代码
done
# while循环
COUNT=1
echo “Counting to 5 with while:”
while [ $COUNT -le 5 ]; do
echo "Number: $COUNT"
COUNT=$((COUNT + 1))
复制代码
done
# until循环
COUNT=1
echo “Counting to 5 with until:”
until [ $COUNT -gt 5 ]; do
echo "Number: $COUNT"
COUNT=$((COUNT + 1))
复制代码
done
# 遍历文件
echo “Files in current directory:”
for FILE in *; do
if [ -f "$FILE" ]; then
echo "File: $FILE"
fi
复制代码
done
#### 函数和参数处理
- 函数定义和调用
```bash
#!/bin/bash
# 定义函数
greet() {
echo "Hello, $1!"
}
# 调用函数
greet "John"
# 带返回值的函数
add() {
local result=$((1 + 2))
echo $result
}
# 捕获返回值
sum=$(add)
echo "1 + 2 = $sum"
# 带多个参数的函数
calculate() {
case $2 in
+) echo $(($1 + $3)) ;;
-) echo $(($1 - $3)) ;;
*) echo "Unknown operator" ;;
esac
}
# 调用函数
result=$(calculate 10 + 5)
echo "10 + 5 = $result"
result=$(calculate 10 - 5)
echo "10 - 5 = $result"
复制代码
• 参数处理
“`bash
#!/bin/bash
# 显示所有参数
echo “All arguments:\(*"
echo "All arguments (quoted): \"\)*\””
echo “All arguments as separate words:\(@"
echo "All arguments as separate words (quoted): \"\)@\””