整理了一个包含多种Shell语法元素的Shell脚本示例,并附有详细的注释。这个脚本展示了变量、条件判断、循环、函数、数组、字符串操作、文件操作等常见的Shell编程技巧,适合初学者学习和参考。
#!/bin/bash
# 1. 变量定义和使用
name="Alice"
age=25
echo "Hello, $name! You are $age years old."
# 2. 只读变量
readonly country="Wonderland"
echo "You are from $country."
# 3. 字符串操作
greeting="Hello, $name!"
echo "Length of greeting: ${#greeting}" # 输出字符串长度
echo "Substring: ${greeting:7:5}" # 输出子字符串
# 4. 数组定义和遍历
fruits=("Apple" "Banana" "Cherry")
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
# 遍历数组
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done
# 5. 条件判断
if [ $age -gt 18 ]; then
echo "$name is an adult."
else
echo "$name is not an adult."
fi
# 6. 多条件判断
if [[ $age -gt 18 && $age -lt 30 ]]; then
echo "$name is a young adult."
elif [[ $age -ge 30 ]]; then
echo "$name is getting older."
else
echo "$name is a teenager."
fi
# 7. case语句
case $age in
18)
echo "$name just became an adult."
;;
25)
echo "$name is 25 years old."
;;
*)
echo "$name is $age years old."
;;
esac
# 8. 循环:for循环
for i in {1..5}; do
echo "For loop iteration $i"
done
# 9. 循环:while循环
counter=0
while [ $counter -lt 3 ]; do
echo "While loop iteration $counter"
counter=$((counter + 1))
done
# 10. 循环:until循环
counter=0
until [ $counter -ge 3 ]; do
echo "Until loop iteration $counter"
counter=$((counter + 1))
done
# 11. 函数定义和调用
function greet() {
local message="Welcome, $1!"
echo "$message"
}
greet "$name"
# 12. 返回值
function add() {
return $(($1 + $2))
}
add 3 4
result=$?
echo "3 + 4 = $result"
# 13. 文件操作
filename="example.txt"
echo "Creating file $filename..."
echo "This is a test file." > $filename
# 检查文件是否存在
if [ -f $filename ]; then
echo "$filename exists."
else
echo "$filename does not exist."
fi
# 读取文件内容
echo "File content:"
cat $filename
# 删除文件
rm $filename
echo "$filename deleted."
# 14. 命令替换
current_date=$(date)
echo "Current date: $current_date"
# 15. 算术运算
a=10
b=5
sum=$((a + b))
echo "Sum of $a and $b is $sum"
# 16. 退出状态码
exit 0
详细注释说明:
- 变量定义和使用:使用
=
定义变量,使用$
引用变量。 - 只读变量:使用
readonly
定义只读变量,不能修改。 - 字符串操作:使用
${#var}
获取字符串长度,使用${var:start:length}
获取子字符串。 - 数组定义和遍历:使用
()
定义数组,使用${array[@]}
遍历数组。 - 条件判断:使用
if
语句进行条件判断,-gt
表示大于,-lt
表示小于。 - 多条件判断:使用
&&
表示逻辑与,||
表示逻辑或。 - case语句:使用
case
语句进行多条件分支判断。 - for循环:使用
for
循环遍历范围或数组。 - while循环:使用
while
循环在条件为真时重复执行。 - until循环:使用
until
循环在条件为假时重复执行。 - 函数定义和调用:使用
function
定义函数,使用local
定义局部变量。 - 返回值:使用
return
返回函数结果,使用$?
获取上一个命令的退出状态。 - 文件操作:使用
>
重定向输出到文件,使用cat
读取文件内容,使用rm
删除文件。 - 命令替换:使用
$(command)
获取命令的输出。 - 算术运算:使用
$((expression))
进行算术运算。 - 退出状态码:使用
exit
指定脚本的退出状态码。
这个脚本涵盖了Shell编程中的大部分常见语法,适合初学者学习和参考。