第163集:条件判断
教学目标
- 掌握Shell脚本中if语句的使用方法
- 熟悉case语句的语法和应用场景
- 学习各种条件表达式的写法
- 理解文件条件判断、数值比较和字符串比较
- 能够在脚本中使用条件判断实现复杂的逻辑控制
主要知识点
- if语句的基本语法
- 嵌套if语句
- case语句的使用
- 条件表达式
- 文件条件判断
- 数值比较
- 字符串比较
实用案例分析
案例1:基本if语句
目标:学习使用基本的if语句进行条件判断。
操作步骤:
- 创建基本if语句演示脚本
# 创建脚本文件
touch basic-if.sh
# 编辑脚本文件
vim basic-if.sh
# 添加以下内容
#!/bin/bash
# 演示基本if语句
# 1. 基本if语句
read -p "Enter a number: " num
if [ $num -gt 0 ]; then
echo "The number is positive."
fi
# 2. if-else语句
read -p "Enter your age: " age
if [ $age -ge 18 ]; then
echo "You are an adult."
else
echo "You are a minor."
fi
# 3. if-elif-else语句
read -p "Enter a grade (A-F): " grade
if [ "$grade" = "A" ]; then
echo "Excellent!"
elif [ "$grade" = "B" ]; then
echo "Good!"
elif [ "$grade" = "C" ]; then
echo "Average."
elif [ "$grade" = "D" ]; then
echo "Below average."
elif [ "$grade" = "F" ]; then
echo "Failed."
else
echo "Invalid grade."
fi- 运行脚本并查看结果
# 设置执行权限
chmod +x basic-if.sh
# 运行脚本
./basic-if.sh案例2:嵌套if语句
目标:学习使用嵌套if语句处理复杂的条件逻辑。
操作步骤:
- 创建嵌套if语句演示脚本
# 创建脚本文件
touch nested-if.sh
# 编辑脚本文件
vim nested-if.sh
# 添加以下内容
#!/bin/bash
# 演示嵌套if语句
read -p "Enter your username: " username
read -s -p "Enter your password: " password
echo
# 嵌套if语句
if [ "$username" = "admin" ]; then
if [ "$password" = "secret" ]; then
echo "Login successful! Welcome, admin."
else
echo "Login failed: Incorrect password."
fi
elif [ "$username" = "user" ]; then
if [ "$password" = "password" ]; then
echo "Login successful! Welcome, user."
else
echo "Login failed: Incorrect password."
fi
else
echo "Login failed: Unknown username."
fi
# 另一个嵌套if示例:检查文件
read -p "Enter a filename: " filename
if [ -e "$filename" ]; then
echo "File exists."
if [ -f "$filename" ]; then
echo "It's a regular file."
elif [ -d "$filename" ]; then
echo "It's a directory."
elif [ -L "$filename" ]; then
echo "It's a symbolic link."
else
echo "It's some other type of file."
fi
else
echo "File does not exist."
fi- 运行脚本并查看结果
# 设置执行权限
chmod +x nested-if.sh
# 运行脚本
./nested-if.sh案例3:case语句
目标:学习使用case语句处理多分支条件判断。
操作步骤:
- 创建case语句演示脚本
# 创建脚本文件
touch case-statement.sh
# 编辑脚本文件
vim case-statement.sh
# 添加以下内容
#!/bin/bash
# 演示case语句
# 1. 基本case语句
read -p "Enter a day of the week: " day
case $day in
Monday|monday|MONDAY)
echo "Today is Monday. Start of the work week."
;;
Tuesday|tuesday|TUESDAY)
echo "Today is Tuesday."
;;
Wednesday|wednesday|WEDNESDAY)
echo "Today is Wednesday. Midweek."
;;
Thursday|thursday|THURSDAY)
echo "Today is Thursday."
;;
Friday|friday|FRIDAY)
echo "Today is Friday. End of the work week!"
;;
Saturday|saturday|SATURDAY|Sunday|sunday|SUNDAY)
echo "Today is a weekend day."
;;
*)
echo "Invalid day."
;;
esac
# 2. case语句处理命令行参数
if [ $# -eq 0 ]; then
echo "Usage: $0 <option>"
echo "Options: start, stop, restart, status"
exit 1
fi
case $1 in
start)
echo "Starting service..."
# 实际服务启动命令
;;
stop)
echo "Stopping service..."
# 实际服务停止命令
;;
restart)
echo "Restarting service..."
# 实际服务重启命令
;;
status)
echo "Checking service status..."
# 实际服务状态检查命令
;;
*)
echo "Invalid option. Use: start, stop, restart, status"
;;
esac- 运行脚本并查看结果
# 设置执行权限
chmod +x case-statement.sh
# 运行脚本(不带参数)
./case-statement.sh
# 运行脚本(带参数)
./case-statement.sh start
./case-statement.sh stop
./case-statement.sh status案例4:条件表达式
目标:学习使用各种条件表达式进行文件、数值和字符串的比较。
操作步骤:
- 创建条件表达式演示脚本
# 创建脚本文件
touch condition-expressions.sh
# 编辑脚本文件
vim condition-expressions.sh
# 添加以下内容
#!/bin/bash
# 演示各种条件表达式
# 1. 文件条件判断
echo "=== File Condition Checks ==="
read -p "Enter a filename: " file
if [ -e "$file" ]; then
echo "File exists"
else
echo "File does not exist"
fi
if [ -f "$file" ]; then
echo "It's a regular file"
elif [ -d "$file" ]; then
echo "It's a directory"
elif [ -L "$file" ]; then
echo "It's a symbolic link"
fi
if [ -r "$file" ]; then
echo "File is readable"
fi
if [ -w "$file" ]; then
echo "File is writable"
fi
if [ -x "$file" ]; then
echo "File is executable"
fi
# 2. 数值比较
echo "\n=== Numeric Comparisons ==="
read -p "Enter first number: " num1
read -p "Enter second number: " num2
if [ $num1 -eq $num2 ]; then
echo "$num1 equals $num2"
elif [ $num1 -ne $num2 ]; then
echo "$num1 not equals $num2"
fi
if [ $num1 -gt $num2 ]; then
echo "$num1 is greater than $num2"
elif [ $num1 -lt $num2 ]; then
echo "$num1 is less than $num2"
elif [ $num1 -ge $num2 ]; then
echo "$num1 is greater than or equal to $num2"
elif [ $num1 -le $num2 ]; then
echo "$num1 is less than or equal to $num2"
fi
# 3. 字符串比较
echo "\n=== String Comparisons ==="
read -p "Enter first string: " str1
read -p "Enter second string: " str2
if [ "$str1" = "$str2" ]; then
echo "Strings are equal"
elif [ "$str1" != "$str2" ]; then
echo "Strings are not equal"
fi
if [ -z "$str1" ]; then
echo "First string is empty"
fi
if [ -n "$str1" ]; then
echo "First string is not empty"
fi
# 4. 逻辑运算符
echo "\n=== Logical Operators ==="
read -p "Enter your age: " age
read -p "Do you have a driver's license? (y/n): " license
if [ $age -ge 18 ] && [ "$license" = "y" ]; then
echo "You can drive."
elif [ $age -lt 18 ] || [ "$license" = "n" ]; then
echo "You cannot drive."
fi- 运行脚本并查看结果
# 设置执行权限
chmod +x condition-expressions.sh
# 运行脚本
./condition-expressions.sh案例5:高级条件判断
目标:学习使用高级条件判断技巧。
操作步骤:
- 创建高级条件判断演示脚本
# 创建脚本文件
touch advanced-conditionals.sh
# 编辑脚本文件
vim advanced-conditionals.sh
# 添加以下内容
#!/bin/bash
# 演示高级条件判断
# 1. 使用双括号进行算术运算和比较
echo "=== Using Double Parentheses ==="
read -p "Enter a number: " num
if (( $num > 10 )); then
echo "The number is greater than 10."
fi
# 2. 使用双方括号进行字符串比较
echo "\n=== Using Double Brackets ==="
read -p "Enter a string: " str
if [[ $str == *"linux"* ]]; then
echo "The string contains 'linux'."
fi
# 3. 组合条件
echo "\n=== Combining Conditions ==="
read -p "Enter your username: " user
read -s -p "Enter your password: " pass
echo
if [[ "$user" == "admin" && "$pass" == "secret" ]]; then
echo "Admin login successful."
elif [[ "$user" == "user" && "$pass" == "password" ]]; then
echo "User login successful."
else
echo "Login failed."
fi
# 4. 条件判断的简写形式
echo "\n=== Short Form Conditionals ==="
read -p "Enter Y/N: " answer
# 简写形式1:
[[ "$answer" == "Y" ]] && echo "You entered Yes"
# 简写形式2:
[[ "$answer" == "N" ]] || echo "You did not enter No"
# 5. 使用test命令
echo "\n=== Using test Command ==="
read -p "Enter a filename: " file
if test -e "$file"; then
echo "File exists"
else
echo "File does not exist"
fi- 运行脚本并查看结果
# 设置执行权限
chmod +x advanced-conditionals.sh
# 运行脚本
./advanced-conditionals.sh课后练习
基础练习
- 创建一个脚本,使用if语句判断一个数是正数、负数还是零
- 编写一个脚本,使用case语句根据用户输入的月份显示季节
- 设计一个脚本,使用条件判断检查文件是否存在并显示其类型
进阶练习
- 创建一个脚本,使用嵌套if语句实现简单的登录系统
- 编写一个脚本,使用条件表达式检查系统资源使用情况并发出警告
- 设计一个脚本,使用case语句实现一个简单的命令行菜单
挑战练习
- 编写一个脚本,使用条件判断实现一个简单的文件管理器
- 创建一个脚本,使用高级条件判断实现一个用户权限管理系统
- 设计一个脚本,使用条件判断和循环实现一个简单的猜数字游戏
总结
本集详细介绍了Linux Shell脚本中的条件判断语句,包括if语句、case语句以及各种条件表达式的使用方法。通过学习这些知识,读者可以在Shell脚本中实现复杂的逻辑控制,根据不同的条件执行不同的操作。
条件判断是Shell脚本编程中的重要组成部分,它允许脚本根据特定条件做出决策,从而实现更灵活、更智能的自动化任务。掌握条件判断的使用是编写复杂Shell脚本的基础。
通过本集的学习,读者应该能够理解和使用基本的if语句、嵌套if语句和case语句,掌握各种条件表达式的写法,以及理解文件条件判断、数值比较和字符串比较的方法。这些知识将为后续学习循环语句和函数定义打下基础。