1 什么是 Shell?
Shell 是一个命令行解释器,它为用户和操作系统之间提供了一个接口。通过 Shell,用户可以执行命令、启动程序和编写脚本。Bash(Bourne Again SHell)是 Linux 中最常用的 Shell 之一。
2 基础语法
2.1 变量定义
# 字符串
my_string="Hello, World!"
# 数字
num=42
# 数组
array=("apple" "banana" "cherry")
# 字典
declare -A my_dict
my_dict["name"]="Alice"
my_dict["age"]=30
2.2 条件判断
#!/bin/bash
num=5
# 使用 [] 进行测试
if [ $num -gt 0 ]; then
echo "The number is positive."
else
echo "The number is not positive."
fi
2.4 循环结构
#!/bin/bash
# 使用for循环
for i in {1..5}; do
echo "Iteration $i"
done
# 使用while循环
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
2.5 使用函数
以下展示了如何使用一个带参数和本地变量的函数:
#!/bin/bash
# 定义函数
calculate_area() {
# 接受第一个参数到某个局部变量
local width=$1
# 接受第二个参数到某个局部变量
local height=$2
local area=$(($width * $height))
echo "Area: $area"
}
# 调用函数
calculate_area 5 3