Shell 编程基础
2025-02-17
1. Shell 基础
1.1 Shell 类型
Shell 是用户与 Linux 系统交互的接口。Linux 支持多种 Shell:
- bash (默认)
- sh
- csh
- zsh
# 查看当前 Shell
echo $SHELL
# 查看可用 Shell
cat /etc/shells
# 切换 Shell
chsh -s /bin/bash1.2 脚本结构
Shell 脚本通常包含以下部分:
- Shebang 行 (#!/bin/bash)
- 注释说明
- 变量定义
- 主要命令
- 函数定义
#!/bin/bash
# 脚本说明:这是一个示例脚本
# 变量定义
name="value"
# 命令执行
command
# 函数定义
function_name() {
commands
}2. 变量和参数
2.1 变量操作
Shell 变量分为:
- 用户定义变量
- 环境变量
- 特殊变量
# 定义变量
name="John"
age=25
# 使用变量
echo $name
echo ${name}
# 只读变量
readonly name
# 删除变量
unset age
# 环境变量
export PATH="$PATH:/new/path"2.2 特殊变量
Shell 提供了一些特殊变量用于获取脚本信息:
| 变量 | 说明 |
|---|---|
| $0 | 脚本名称 |
| $1 | 第一个参数 |
| $# | 参数个数 |
| $* | 所有参数 |
| $@ | 所有参数(数组形式) |
| $? | 上一个命令的返回值 |
| $$ | 当前进程 ID |
| $! | 最后一个后台进程的 PID |
3. 流程控制
3.1 条件判断
# if 语句
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
# case 语句
case $var in
pattern1)
commands
;;
pattern2)
commands
;;
*)
commands
;;
esac3.2 循环
# for 循环
for i in item1 item2 item3; do
commands
done
# while 循环
while [ condition ]; do
commands
done
# until 循环
until [ condition ]; do
commands
done4. 函数
4.1 函数定义
# 基本函数
function name() {
commands
return value
}
# 带参数的函数
function print_params() {
echo "First: $1"
echo "Second: $2"
}4.2 函数调用
# 调用函数
name
# 带参数调用
print_params "hello" "world"
# 获取返回值
result=$?5. 文件操作
5.1 文件读写
# 读取文件
while read line; do
echo $line
done < file.txt
# 写入文件
echo "content" > file.txt
echo "append" >> file.txt5.2 文件状态测试
# 文件存在
[ -e file ]
# 是否是目录
[ -d dir ]
# 是否是文件
[ -f file ]
# 是否可读
[ -r file ]6. 字符串处理
6.1 字符串操作
# 字符串长度
${#string}
# 字符串截取
${string:position:length}
# 字符串替换
${string/pattern/replacement}6.2 正则表达式
# 使用 grep
grep "pattern" file
# 使用 sed
sed 's/old/new/g' file
# 使用 awk
awk '/pattern/ {print $1}' file7. 调试技巧
7.1 调试选项
# 打开调试
set -x
# 关闭调试
set +x
# 检查语法
bash -n script.sh7.2 错误处理
# 错误退出
set -e
# 捕获错误
trap 'echo Error at line $LINENO' ERR
# 自定义错误处理
error_handler() {
echo "Error: $1"
exit 1
}