number=5# gt lt 分别是 > 和 <if [ $number -gt 0 ]; then echo "The number is positive."elif [ $number -lt 0 ]; then echo "The number is negative."else echo "The number is zero."fi
复制代码
case 语句
case "$variable" in
pattern1)
# statements
;;
pattern2)
# statements
;;
*)
# default statements
;;
esac
复制代码
样例:
#!/bin/bash
echo "Enter a single character (a-g):"read charcase "$char" in a) echo "Monday" ;; b) echo "Tuesday" ;; c) echo "Wednesday" ;; d) echo "Thursday" ;; e) echo "Friday" ;; f) echo "Saturday" ;; g) echo "Sunday" ;; *) echo "Invalid input" ;;esac
复制代码
test 下令
test 下令用于条件判定,常与逻辑运算符结合使用。
文件测试
-e 文件存在
-f 文件是平凡文件
-d 文件是目次
if test -e /etc/passwd; then
echo "/etc/passwd exists."
fi
复制代码
字符串测试
-z 字符串为空
-n 字符串非空
= 字符串相称
!= 字符串不相称
if test -z "$name"; then
echo "Name is empty."
fi
复制代码
数值测试
-eq 即是
-ne 不即是
-gt 大于
-lt 小于
-ge 大于或即是
-le 小于或即是
if test $age -gt 20; then
echo "Age is greater than 20."
fi
复制代码
7. 循环语句
for 循环
for var in list; do
# statements
done
复制代码
for i in {1..5}; do
echo "Number: $i"
done
复制代码
while 循环
while [ condition ]; do
# statements
done
复制代码
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
counter=$((counter + 1))
done
复制代码
until 循环
until [ condition ]; do
# statements
done
复制代码
counter=1
until [ $counter -gt 5]; do
echo "Counter: $counter"
counter=$((counter + 1))
done
复制代码
8. 函数
Shell 函数用于封装代码块,以便多次调用。
定义函数
function_name() {
# statements
}
复制代码
greet() {
echo "Hello, $1!"
}
greet "World"
复制代码
带返回值的函数
add() {
result=$(( $1 + $2 ))
return $result
}
add 2 3
echo "Sum: $?"
复制代码
综合示例
#!/bin/bash
# 函数定义print_menu() { echo "1. Say Hello" echo "2. Display Date" echo "3. Exit"}# 主程序while true; do print_menu read -p "Enter your choice: " choice case $choice in 1) read -p "Enter your name: " name echo "Hello, $name!" ;; 2) current_date=$(date) echo "Current date and time: $current_date" ;; 3) echo "Goodbye!" break ;; *) echo "Invalid choice, please try again." ;; esacdone