当前位置:首页>Linux>Shell 命令全解:Linux/Unix 命令行终极指南

Shell 命令全解:Linux/Unix 命令行终极指南

  • 2026-01-22 12:34:18
Shell 命令全解:Linux/Unix 命令行终极指南

一、Shell 基础概念与分类

1.1 Shell 是什么?

Shell 是操作系统的命令行界面,它是用户与操作系统内核之间的接口程序,负责解释和执行用户输入的命令。

1.2 Shell 的主要类型

```bash
# 查看当前使用的Shell
echo $SHELL
echo $0

# 查看系统可用的Shell
cat /etc/shells

# 切换Shell
chsh -s /bin/bash # 更改默认Shell
exec /bin/zsh # 临时切换当前会话
```

Shell 类型对比表:

Shell 名称 推出时间 特点 配置文件
Bash (Bourne-Again Shell) 1989 GNU项目,最流行,功能丰富 ~/.bashrc, ~/.bash_profile
Zsh (Z Shell) 1990 功能强大,主题丰富,社区活跃 ~/.zshrc
Fish (Friendly Interactive Shell) 2005 用户友好,自动建议,语法高亮 ~/.config/fish/config.fish
Dash (Debian Almquist Shell) 2002 POSIX兼容,轻量快速 /etc/dashrc
Ksh (Korn Shell) 1983 商业版,高级脚本功能 ~/.kshrc
Tcsh (TENEX C Shell) 1978 C语法,命令行编辑 ~/.tcshrc, ~/.cshrc

1.3 Shell 启动流程

```
登录流程:
┌─────────────────────────────────────────┐
│ /etc/profile │
│ ├── /etc/profile.d/*.sh │
│ └── /etc/bashrc 或 /etc/bash.bashrc │
├─────────────────────────────────────────┤
│ ~/.bash_profile 或 ~/.bash_login │
│ ├── ~/.profile (如果没有上述文件) │
│ └── ~/.bashrc │
└─────────────────────────────────────────┘

非登录Shell启动:
┌─────────────────────────────────────────┐
│ ~/.bashrc │
│ └── /etc/bashrc │
└─────────────────────────────────────────┘
```

二、Shell 基本语法与特性

2.1 命令结构

```bash
# 基本格式
命令 [选项] [参数]

# 示例
ls -la /home
grep -r "error" /var/log
```

2.2 特殊字符与元字符

字符 作用 示例
**` `** 管道,连接命令
> 输出重定向(覆盖) echo "text" > file.txt
>> 输出重定向(追加) echo "more" >> file.txt
< 输入重定向 wc -l < file.txt
& 后台运行 sleep 10 &
; 命令分隔符 cd /tmp; ls; pwd
&& 逻辑与(成功才执行) mkdir test && cd test
**` `**
# 注释 # 这是一条注释
$ 变量引用 echo $PATH
* 通配符(匹配任意字符) ls *.txt
? 通配符(匹配单个字符) ls file?.txt
[] 字符范围 ls file[1-3].txt
{} 命令块或扩展 echo {1..10}
~ 用户主目录 cd ~
\ 转义字符 echo "Price: \$100"
" 弱引用(允许变量扩展) echo "User: $USER"
' 强引用(禁止扩展) echo 'User: $USER'
` 命令替换(旧语法) echo "Today is date"
$() 命令替换(新语法) echo "Today is $(date)"

2.3 输入输出重定向

标准文件描述符:

· 0 - stdin(标准输入)
· 1 - stdout(标准输出)
· 2 - stderr(标准错误)

```bash
# 重定向示例
ls > files.txt # 标准输出到文件
ls 2> errors.txt # 标准错误到文件
ls > output.txt 2>&1 # 标准输出和错误到同一文件
ls &> all_output.txt # 同上(Bash特有)
ls > /dev/null # 丢弃输出

# 输入重定向
wc -l < file.txt # 从文件读取输入
cat << EOF # Here Document
> Line 1
> Line 2
> EOF

# 追加重定向
echo "new line" >> log.txt
```

2.4 管道与命令组合

```bash
# 简单管道
ps aux | grep ssh
cat file.txt | sort | uniq

# 复杂管道
find /var/log -name "*.log" -type f -mtime -7 | \
xargs grep -l "ERROR" | \
while read file; do
echo "Found errors in: $file"
grep -c "ERROR" "$file"
done

# 命令组合
(cd /tmp && ls -la) # 子Shell执行
{ cd /tmp && ls -la; } # 当前Shell执行
```

三、Shell 变量与环境

3.1 变量定义与使用

```bash
# 变量定义(等号两边不能有空格)
name="John Doe"
count=42
files=$(ls) # 命令替换

# 变量使用
echo $name # 简单引用
echo ${name} # 明确边界
echo "${name}'s files" # 带引号的扩展

# 只读变量
readonly PI=3.14159
declare -r MAX_USERS=100

# 删除变量
unset name
```

3.2 特殊Shell变量

变量 说明 示例
$0 脚本或Shell名称 echo "Script: $0"
$1-$9 位置参数1-9 echo "First arg: $1"
$# 参数个数 echo "Args count: $#"
$@ 所有参数列表 for arg in "$@"; do echo "$arg"; done
$* 所有参数(一个字符串) echo "All args: $*"
$? 上条命令退出状态 ls; echo "Exit code: $?"
$$ 当前进程PID echo "PID: $$"
$! 最后一个后台进程PID sleep 10 & echo "BG PID: $!"

3.3 环境变量

```bash
# 查看环境变量
env # 所有环境变量
printenv # 同上
printenv HOME # 特定变量
echo $PATH # 直接引用

# 常用环境变量
echo "用户: $USER" # 当前用户名
echo "主机: $HOSTNAME" # 主机名
echo "主目录: $HOME" # 用户主目录
echo "提示符: $PS1" # 主提示符
echo "路径: $PATH" # 命令搜索路径
echo "语言: $LANG" # 系统语言
echo "Shell: $SHELL" # 默认Shell
echo "终端: $TERM" # 终端类型
echo "编辑器: $EDITOR" # 默认编辑器

# 设置环境变量
export JAVA_HOME=/opt/java # 当前会话和子进程
export PATH=$PATH:/opt/bin # 添加到PATH

# 持久化环境变量
# 添加到 ~/.bashrc 或 ~/.bash_profile
echo 'export MY_VAR="value"' >> ~/.bashrc
source ~/.bashrc # 重新加载配置
```

3.4 数组与关联数组

```bash
# 索引数组
fruits=("apple" "banana" "cherry")
fruits[3]="date"
echo ${fruits[0]} # apple
echo ${fruits[@]} # 所有元素
echo ${#fruits[@]} # 数组长度
echo ${!fruits[@]} # 所有索引

# 循环数组
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done

# 关联数组(Bash 4.0+)
declare -A user
user[name]="Alice"
user[age]=30
user[email]="alice@example.com"

echo "Name: ${user[name]}"
for key in "${!user[@]}"; do
echo "$key: ${user[$key]}"
done
```

四、Shell 常用命令详解

4.1 文件与目录操作

导航与查看

```bash
# 目录操作
pwd # 显示当前目录
cd /path/to/dir # 切换目录
cd ~ # 切换到主目录
cd - # 切换到上一个目录
cd .. # 切换到父目录
pushd /tmp # 保存当前目录并切换
popd # 返回保存的目录
dirs # 显示目录栈

# 目录内容
ls # 列出文件
ls -l # 详细列表
ls -a # 显示隐藏文件
ls -la # 详细列表含隐藏文件
ls -lh # 人类可读大小
ls -lt # 按时间排序
ls -ltr # 按时间逆序
ls -R # 递归列出
tree # 树状显示(需安装)
```

文件操作

```bash
# 创建文件
touch file.txt # 创建空文件或更新时间戳
touch file{1..10}.txt # 创建多个文件
> file.txt # 创建空文件(重定向)

# 创建目录
mkdir dirname # 创建目录
mkdir -p /path/to/dir # 创建多级目录
mkdir dir{1..5} # 创建多个目录

# 复制文件/目录
cp file1.txt file2.txt # 复制文件
cp -r dir1 dir2 # 递归复制目录
cp -p file.txt backup/ # 保留属性
cp -u source dest # 仅复制更新的文件
cp -v file.txt dest/ # 显示详细信息

# 移动/重命名
mv old.txt new.txt # 重命名文件
mv file.txt /dest/ # 移动文件
mv -i file.txt dest/ # 交互式移动
mv -n file.txt dest/ # 不覆盖已存在文件
mv -v *.txt archive/ # 显示移动详情

# 删除
rm file.txt # 删除文件
rm -r dirname # 递归删除目录
rm -f file.txt # 强制删除(不提示)
rm -rf dirname # 强制递归删除
rmdir dirname # 删除空目录
```

文件查看与编辑

```bash
# 查看文件内容
cat file.txt # 显示整个文件
cat -n file.txt # 显示行号
tac file.txt # 反向显示
less file.txt # 分页查看
more file.txt # 分页查看(旧版)
head -n 10 file.txt # 查看前10行
tail -n 20 file.txt # 查看后20行
tail -f log.txt # 实时跟踪文件变化

# 文件比较
diff file1.txt file2.txt # 比较文件差异
diff -u file1.txt file2.txt # 统一格式差异
cmp file1.txt file2.txt # 比较二进制文件
md5sum file.txt # 计算MD5哈希
sha256sum file.txt # 计算SHA256哈希

# 文本处理
wc file.txt # 统计行数、单词数、字符数
wc -l file.txt # 只统计行数
wc -w file.txt # 只统计单词数
wc -c file.txt # 只统计字符数
```

4.2 文本处理命令

grep 系列(文本搜索)

```bash
# 基本搜索
grep "pattern" file.txt # 搜索包含pattern的行
grep -i "error" log.txt # 忽略大小写
grep -v "debug" log.txt # 反向匹配(不包含)
grep -n "warning" log.txt # 显示行号
grep -c "error" log.txt # 统计匹配行数
grep -l "pattern" *.txt # 显示包含匹配的文件名
grep -r "TODO" . # 递归搜索目录
grep -E "error|warning" log.txt # 扩展正则表达式

# 高级用法
grep -B 2 "error" log.txt # 显示匹配行前2行
grep -A 3 "error" log.txt # 显示匹配行后3行
grep -C 2 "error" log.txt # 显示匹配行前后各2行
grep -o "http[^ ]*" file.txt # 只显示匹配部分
grep -P "regex" file.txt # Perl正则表达式
```

sed(流编辑器)

```bash
# 基本替换
sed 's/old/new/g' file.txt # 全局替换
sed 's/old/new/2' file.txt # 替换每行第2个匹配
sed -i 's/old/new/g' file.txt # 直接修改文件
sed -i.bak 's/old/new/g' file.txt # 备份后修改

# 删除行
sed '1d' file.txt # 删除第1行
sed '$d' file.txt # 删除最后1行
sed '1,5d' file.txt # 删除1-5行
sed '/pattern/d' file.txt # 删除匹配行

# 其他操作
sed -n '10,20p' file.txt # 打印10-20行
sed '5i\新行内容' file.txt # 在第5行前插入
sed '5a\新行内容' file.txt # 在第5行后插入
sed 'y/abc/ABC/' file.txt # 字符转换
sed '/pattern/,+2d' file.txt # 删除匹配行及后2行
```

awk(文本处理语言)

```bash
# 基本用法
awk '{print $1}' file.txt # 打印第1列
awk '{print $NF}' file.txt # 打印最后一列
awk -F: '{print $1}' /etc/passwd # 指定分隔符为冒号
awk -F'[ ,]' '{print $2}' file.txt # 多个分隔符

# 条件过滤
awk '$3 > 100 {print $1, $3}' file.txt # 第3列大于100
awk '/error/ {print $0}' log.txt # 包含error的行
awk 'NR==1 || NR==10' file.txt # 第1行和第10行
awk 'NR>=10 && NR<=20' file.txt # 10-20行

# 计算与统计
awk '{sum+=$3} END {print sum}' file.txt # 第3列求和
awk '{avg+=$3} END {print avg/NR}' file.txt # 第3列平均值
awk '{count[$1]++} END {for (i in count) print i, count[i]}' file.txt # 第1列频率统计

# 内置变量
awk '{print FILENAME, NR, FNR, NF}' file.txt
# FILENAME - 当前文件名
# NR - 总记录数(行号)
# FNR - 当前文件记录数
# NF - 当前行字段数
```

其他文本工具

```bash
# sort 排序
sort file.txt # 字典序排序
sort -n file.txt # 数值排序
sort -r file.txt # 逆序排序
sort -u file.txt # 去重排序
sort -k2,2n file.txt # 按第2列数值排序
sort -t, -k3 file.txt # 逗号分隔,按第3列排序

# uniq 去重
uniq file.txt # 去除相邻重复行
uniq -c file.txt # 统计重复次数
uniq -d file.txt # 只显示重复行
uniq -u file.txt # 只显示唯一行
sort file.txt | uniq # 全局去重

# cut 列提取
cut -d: -f1 /etc/passwd # 冒号分隔,取第1列
cut -c1-10 file.txt # 取1-10个字符
cut -c2- file.txt # 从第2个字符到最后

# paste 合并
paste file1.txt file2.txt # 并排合并文件
paste -d, file1.txt file2.txt # 指定分隔符
paste -s file.txt # 将多行合并为一行

# tr 字符转换
tr 'a-z' 'A-Z' < file.txt # 小写转大写
tr -d '\r' < file.txt # 删除回车符
tr -s ' ' < file.txt # 压缩连续空格
tr -d '0-9' < file.txt # 删除数字
```

4.3 系统信息与管理

系统状态

```bash
# 系统信息
uname -a # 所有系统信息
uname -r # 内核版本
uname -m # 机器架构
hostname # 主机名
hostname -I # 所有IP地址
uptime # 系统运行时间
who # 登录用户
whoami # 当前用户
w # 详细登录信息

# 日期时间
date # 当前日期时间
date +"%Y-%m-%d %H:%M:%S" # 格式输出
date -d "2024-01-01" +%s # 转换为时间戳
date -d @1672531200 # 时间戳转日期
cal # 本月日历
cal -y # 全年日历
cal 12 2024 # 指定年月日历
```

进程管理

```bash
# 进程查看
ps # 当前终端进程
ps aux # 所有进程
ps -ef # 完整格式
ps aux --sort=-%cpu # 按CPU排序
ps aux --sort=-%mem # 按内存排序
ps -p 1234 # 指定PID进程
ps -u username # 指定用户进程

# top/htop 实时监控
top # 实时进程监控
top -u username # 监控指定用户
htop # 增强版top(需安装)
top -b -n 1 > process.txt # 批处理模式

# 进程控制
kill 1234 # 发送TERM信号
kill -9 1234 # 强制终止
kill -15 1234 # 发送TERM信号
kill -l # 列出所有信号
killall process_name # 终止同名进程
pkill -f "pattern" # 按模式终止进程

# 后台作业
sleep 30 & # 后台运行
jobs # 查看后台作业
fg %1 # 前台运行作业1
bg %2 # 后台继续作业2
ctrl+z # 暂停当前作业
```

内存与磁盘

```bash
# 内存信息
free # 内存使用情况
free -h # 人类可读格式
free -m # MB单位
vmstat 1 5 # 虚拟内存统计
vmstat -s # 统计摘要

# 磁盘信息
df # 磁盘使用情况
df -h # 人类可读格式
df -i # inode使用情况
df -T # 显示文件系统类型
du # 目录大小
du -sh dirname # 目录总大小
du -h --max-depth=1 dirname # 一级子目录大小
du -sh * # 当前目录各文件大小
```

网络管理

```bash
# 网络配置
ifconfig # 网络接口配置(旧)
ip addr # IP地址信息
ip route # 路由表
ip link # 网络接口
netstat # 网络状态
ss # Socket统计(新)
route -n # 路由表

# 网络测试
ping google.com # 测试连通性
ping -c 5 google.com # 指定次数
traceroute google.com # 路由跟踪
mtr google.com # 增强路由跟踪
nslookup google.com # DNS查询
dig google.com # DNS查询(详细)
host google.com # DNS查询(简单)

# 网络连接
netstat -tulpn # 监听端口
ss -tulpn # 监听端口(新)
netstat -an # 所有连接
lsof -i :80 # 查看80端口进程
```

4.4 用户与权限管理

用户管理

```bash
# 用户信息
id # 当前用户ID
id username # 指定用户ID
whoami # 当前用户名
who # 登录用户
last # 登录历史
lastlog # 最近登录
finger username # 用户信息

# 用户操作(需root)
useradd newuser # 添加用户
useradd -m -s /bin/bash newuser # 创建家目录并指定shell
userdel username # 删除用户
userdel -r username # 删除用户及家目录
usermod -aG groupname username # 添加用户到组
passwd username # 修改用户密码
chsh -s /bin/zsh username # 更改用户shell
```

组管理

```bash
# 组操作
groups # 当前用户所属组
groups username # 指定用户所属组
id -Gn username # 用户组ID
groupadd newgroup # 添加组
groupdel groupname # 删除组
gpasswd -a user group # 添加用户到组
gpasswd -d user group # 从组移除用户
newgrp groupname # 切换主组(临时)
```

文件权限

```bash
# 权限查看
ls -l file.txt # 查看文件权限
stat file.txt # 详细文件信息

# 权限修改
chmod 755 script.sh # 数字模式
chmod u+x file.txt # 为用户添加执行权限
chmod g-w file.txt # 移除组写权限
chmod o=r file.txt # 设置其他用户只读
chmod a+x script.sh # 为所有用户添加执行权限
chmod -R 755 directory/ # 递归修改目录权限

# 所有者和组
chown user:group file.txt # 修改所有者和组
chown user file.txt # 仅修改所有者
chgrp group file.txt # 仅修改组
chown -R user:group directory/ # 递归修改

# 特殊权限
chmod +t directory/ # 设置粘滞位
chmod u+s program # 设置SUID
chmod g+s directory/ # 设置SGID
```

sudo 权限

```bash
# sudo使用
sudo command # 以root执行命令
sudo -i # 切换到root shell
sudo -u username command # 以其他用户执行
sudo -l # 列出可执行的命令

# 配置sudoers(使用visudo编辑)
# /etc/sudoers 或 /etc/sudoers.d/
username ALL=(ALL) ALL # 完全权限
username ALL=(ALL) NOPASSWD:ALL # 无需密码
%groupname ALL=(ALL) ALL # 组权限
username ALL=(root) /usr/bin/apt # 特定命令
```

4.5 包管理器

APT (Debian/Ubuntu)

```bash
# 更新源
sudo apt update # 更新包列表
sudo apt upgrade # 升级所有包
sudo apt full-upgrade # 完全升级

# 包管理
sudo apt install package # 安装包
sudo apt install package1 package2 # 安装多个包
sudo apt remove package # 移除包
sudo apt purge package # 移除包及配置文件
sudo apt autoremove # 自动移除不需要的包

# 搜索与信息
apt search keyword # 搜索包
apt show package # 显示包信息
apt list --installed # 已安装包列表
apt list --upgradable # 可升级包列表
apt depends package # 依赖关系
apt-cache policy package # 包版本策略
```

YUM/DNF (RHEL/CentOS/Fedora)

```bash
# YUM (较旧系统)
sudo yum update # 更新系统
sudo yum install package # 安装包
sudo yum remove package # 移除包
sudo yum search keyword # 搜索包
sudo yum info package # 包信息
sudo yum list installed # 已安装包

# DNF (新一代,Fedora/RHEL8+)
sudo dnf update # 更新系统
sudo dnf install package # 安装包
sudo dnf remove package # 移除包
sudo dnf search keyword # 搜索包
sudo dnf info package # 包信息
sudo dnf history # 操作历史
```

Pacman (Arch Linux)

```bash
# 包管理
sudo pacman -Syu # 更新系统
sudo pacman -S package # 安装包
sudo pacman -Rs package # 移除包及依赖
sudo pacman -Qe # 显式安装的包
sudo pacman -Qdt # 孤立包(可移除)

# 查询
pacman -Ss keyword # 搜索包
pacman -Qi package # 包信息
pacman -Ql package # 包文件列表
pacman -U package.pkg.tar.zst # 安装本地包
```

五、Shell 脚本编程

5.1 脚本基础

```bash
#!/bin/bash
# 脚本第一行:shebang,指定解释器
# 这是注释

# 脚本示例:hello.sh
#!/bin/bash

echo "Hello, World!"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo "Date: $(date)"

# 执行脚本
chmod +x hello.sh # 添加执行权限
./hello.sh # 执行脚本
bash hello.sh # 直接指定解释器执行
```

5.2 变量与参数

```bash
#!/bin/bash
# variables.sh

# 位置参数
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Number of arguments: $#"

# 特殊参数处理
echo "Last argument: ${!#}"
echo "All arguments as one string: $*"

# 参数默认值
name=${1:-"Guest"} # 如果$1为空,使用"Guest"
count=${2:-10} # 如果$2为空,使用10
echo "Name: $name"
echo "Count: $count"

# 参数检查
if [ $# -eq 0 ]; then
echo "Usage: $0 <name> [count]"
exit 1
fi
```

5.3 流程控制

条件判断

```bash
#!/bin/bash
# condition.sh

# 数字比较
a=10
b=20

if [ $a -eq $b ]; then
echo "a equals b"
elif [ $a -lt $b ]; then
echo "a less than b"
else
echo "a greater than b"
fi

# 字符串比较
str1="hello"
str2="world"

if [ "$str1" = "$str2" ]; then
echo "Strings are equal"
elif [ "$str1" != "$str2" ]; then
echo "Strings are different"
fi

# 文件测试
file="/etc/passwd"

if [ -f "$file" ]; then
echo "$file exists and is a regular file"
fi

if [ -d "/tmp" ]; then
echo "/tmp is a directory"
fi

if [ -r "$file" ]; then
echo "$file is readable"
fi

if [ -w "$file" ]; then
echo "$file is writable"
fi

if [ -x "/bin/bash" ]; then
echo "/bin/bash is executable"
fi

# 组合条件
if [ -f "$file" ] && [ -r "$file" ]; then
echo "$file exists and is readable"
fi

if [ ! -d "/nonexistent" ]; then
echo "/nonexistent does not exist or is not a directory"
fi
```

循环结构

```bash
#!/bin/bash
# loops.sh

# for循环
echo "For loop 1-5:"
for i in 1 2 3 4 5; do
echo "Number: $i"
done

echo "For loop range:"
for i in {1..5}; do
echo "Number: $i"
done

echo "For loop with step:"
for i in {1..10..2}; do
echo "Number: $i"
done

echo "For loop over files:"
for file in *.txt; do
echo "Processing: $file"
done

echo "C-style for loop:"
for ((i=0; i<5; i++)); do
echo "i = $i"
done

# while循环
echo "While loop:"
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done

# 读取文件行
echo "Reading file line by line:"
while IFS= read -r line; do
echo "Line: $line"
done < /etc/passwd

# until循环
echo "Until loop:"
num=1
until [ $num -gt 5 ]; do
echo "Num: $num"
((num++))
done

# 无限循环
# while true; do
# echo "Running..."
# sleep 1
# done
```

case 语句

```bash
#!/bin/bash
# case.sh

read -p "Enter a fruit: " fruit

case $fruit in
apple)
echo "You chose apple"
echo "It's red and sweet"
;;
banana)
echo "You chose banana"
echo "It's yellow and curved"
;;
orange|grapefruit)
echo "You chose citrus fruit"
;;
*)
echo "Unknown fruit: $fruit"
;;
esac

# 模式匹配
read -p "Enter filename: " filename

case $filename in
*.txt)
echo "Text file"
;;
*.jpg|*.png|*.gif)
echo "Image file"
;;
script.*)
echo "Script file"
;;
*)
echo "Other file type"
;;
esac
```

5.4 函数

```bash
#!/bin/bash
# functions.sh

# 基本函数
say_hello() {
echo "Hello, $1!"
}

say_hello "World"
say_hello "Alice"

# 返回值函数
add() {
local result=$(( $1 + $2 ))
echo $result # 通过echo返回值
}

sum=$(add 10 20)
echo "Sum: $sum"

# 函数参数
show_info() {
echo "Function name: $FUNCNAME"
echo "Number of arguments: $#"
echo "All arguments: $@"
echo "First argument: $1"
echo "Second argument: $2"
}

show_info "arg1" "arg2" "arg3"

# 局部变量
counter=0

increment() {
local counter=10 # 局部变量
((counter++))
echo "Inside function: counter=$counter"
}

increment
echo "Outside function: counter=$counter"

# 递归函数
factorial() {
local n=$1
if [ $n -le 1 ]; then
echo 1
else
local prev=$(factorial $((n-1)))
echo $((n * prev))
fi
}

echo "Factorial of 5: $(factorial 5)"
```

5.5 错误处理

```bash
#!/bin/bash
# error-handling.sh

# 错误退出
set -e # 遇到错误立即退出
# set +e # 关闭错误退出

# 捕获错误
cleanup() {
echo "Cleaning up..."
# 清理临时文件等
}

trap cleanup EXIT # 脚本退出时执行cleanup
trap 'echo "Interrupted!"; exit 1' INT # 捕获Ctrl+C

# 检查命令是否存在
check_command() {
if ! command -v "$1" &> /dev/null; then
echo "Error: $1 is not installed"
exit 1
fi
}

check_command "curl"
check_command "jq"

# 检查文件是否存在
if [ ! -f "required.txt" ]; then
echo "Error: required.txt not found" >&2
exit 1
fi

# 检查目录是否可写
if [ ! -w "/tmp" ]; then
echo "Error: /tmp is not writable" >&2
exit 1
fi

# 函数错误处理
safe_operation() {
local file="$1"

if [ ! -f "$file" ]; then
return 1 # 返回非0表示错误
fi

# 操作文件...
return 0 # 成功
}

if safe_operation "somefile.txt"; then
echo "Operation succeeded"
else
echo "Operation failed"
fi
```

5.6 高级脚本技巧

```bash
#!/bin/bash
# advanced-script.sh

# 读取用户输入
read -p "Enter your name: " name
read -sp "Enter your password: " password # 静默输入
echo
echo "Hello, $name"

# 选择菜单
PS3="Please choose an option: "
options=("Option 1" "Option 2" "Option 3" "Quit")

select opt in "${options[@]}"
do
case $opt in
"Option 1")
echo "You chose Option 1"
;;
"Option 2")
echo "You chose Option 2"
;;
"Option 3")
echo "You chose Option 3"
;;
"Quit")
break
;;
*) echo "Invalid option";;
esac
done

# 数组操作
fruits=("apple" "banana" "cherry")

# 遍历数组
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done

# 数组长度
echo "Number of fruits: ${#fruits[@]}"

# 关联数组(Bash 4+)
declare -A user
user[name]="Alice"
user[age]=25
user[city]="New York"

for key in "${!user[@]}"; do
echo "$key: ${user[$key]}"
done

# Here Document
cat << EOF
This is a multi-line
text block using
here document.
EOF

# Here String
tr 'a-z' 'A-Z' <<< "hello world"

# 进程替换
diff <(ls /dir1) <(ls /dir2)

# 时间命令
time ls -la # 测量命令执行时间

# 并行执行
echo {1..5} | xargs -n1 -P5 sleep

# 彩色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

echo -e "${RED}Error message${NC}"
echo -e "${GREEN}Success message${NC}"
```

六、实用脚本示例

6.1 系统监控脚本

```bash
#!/bin/bash
# system-monitor.sh

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 获取系统信息
get_system_info() {
echo -e "${BLUE}=== 系统信息 ===${NC}"
echo "主机名: $(hostname)"
echo "系统: $(uname -s)"
echo "内核版本: $(uname -r)"
echo "架构: $(uname -m)"
echo "运行时间: $(uptime -p)"
}

# 获取CPU信息
get_cpu_info() {
echo -e "${BLUE}=== CPU信息 ===${NC}"
echo "CPU型号: $(grep 'model name' /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)"
echo "核心数: $(grep -c '^processor' /proc/cpuinfo)"
echo "负载: $(uptime | awk -F'load average:' '{print $2}')"

# CPU使用率
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print 100 - $8}')
if (( $(echo "$cpu_usage > 80" | bc -l) )); then
echo -e "CPU使用率: ${RED}${cpu_usage}%${NC}"
elif (( $(echo "$cpu_usage > 50" | bc -l) )); then
echo -e "CPU使用率: ${YELLOW}${cpu_usage}%${NC}"
else
echo -e "CPU使用率: ${GREEN}${cpu_usage}%${NC}"
fi
}

# 获取内存信息
get_memory_info() {
echo -e "${BLUE}=== 内存信息 ===${NC}"

# 使用free命令获取内存信息
total_mem=$(free -h | grep Mem | awk '{print $2}')
used_mem=$(free -h | grep Mem | awk '{print $3}')
free_mem=$(free -h | grep Mem | awk '{print $4}')
available_mem=$(free -h | grep Mem | awk '{print $7}')

echo "总内存: $total_mem"
echo "已使用: $used_mem"
echo "空闲: $free_mem"
echo "可用: $available_mem"

# 计算使用百分比
total_mem_kb=$(free | grep Mem | awk '{print $2}')
used_mem_kb=$(free | grep Mem | awk '{print $3}')
mem_percent=$((used_mem_kb * 100 / total_mem_kb))

if [ $mem_percent -gt 80 ]; then
echo -e "内存使用率: ${RED}${mem_percent}%${NC}"
elif [ $mem_percent -gt 60 ]; then
echo -e "内存使用率: ${YELLOW}${mem_percent}%${NC}"
else
echo -e "内存使用率: ${GREEN}${mem_percent}%${NC}"
fi
}

# 获取磁盘信息
get_disk_info() {
echo -e "${BLUE}=== 磁盘信息 ===${NC}"

# 获取磁盘使用情况
df -h | grep -E '^/dev/' | while read line; do
filesystem=$(echo $line | awk '{print $1}')
size=$(echo $line | awk '{print $2}')
used=$(echo $line | awk '{print $3}')
avail=$(echo $line | awk '{print $4}')
use_percent=$(echo $line | awk '{print $5}' | tr -d '%')
mount=$(echo $line | awk '{print $6}')

if [ $use_percent -gt 90 ]; then
echo -e "${RED}警告: ${filesystem} (${mount}) 使用 ${use_percent}%${NC}"
elif [ $use_percent -gt 70 ]; then
echo -e "${YELLOW}注意: ${filesystem} (${mount}) 使用 ${use_percent}%${NC}"
else
echo "${filesystem} (${mount}): ${used}/${size} (${use_percent}%)"
fi
done
}

# 获取网络信息
get_network_info() {
echo -e "${BLUE}=== 网络信息 ===${NC}"

# IP地址
echo "IP地址:"
ip -4 addr show | grep inet | awk '{print $2}' | head -5

# 网络接口
echo -e "\n网络接口:"
ip link show | grep -E '^[0-9]+:' | awk -F: '{print $2}' | tr -d ' '

# 连接数
tcp_connections=$(ss -tun | tail -n +2 | wc -l)
echo -e "\nTCP连接数: $tcp_connections"
}

# 获取进程信息
get_process_info() {
echo -e "${BLUE}=== 进程信息 ===${NC}"

# 按CPU使用率排序
echo "Top 5 CPU使用进程:"
ps aux --sort=-%cpu | head -6 | tail -5 | awk '{printf "%-10s %-10s %-10s %s\n", $1, $2, $3"%", $11}'

# 按内存使用率排序
echo -e "\nTop 5 内存使用进程:"
ps aux --sort=-%mem | head -6 | tail -5 | awk '{printf "%-10s %-10s %-10s %s\n", $1, $2, $4"%", $11}'
}

# 主函数
main() {
clear
echo -e "${GREEN}=== 系统监控报告 ===${NC}"
echo "生成时间: $(date)"
echo ""

get_system_info
echo ""

get_cpu_info
echo ""

get_memory_info
echo ""

get_disk_info
echo ""

get_network_info
echo ""

get_process_info
echo ""

echo -e "${GREEN}=== 报告结束 ===${NC}"
}

# 执行主函数
main
```

6.2 日志分析脚本

```bash
#!/bin/bash
# log-analyzer.sh

# 配置
LOG_DIR="/var/log"
OUTPUT_FILE="/tmp/log_analysis_$(date +%Y%m%d_%H%M%S).txt"
ERROR_THRESHOLD=10

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 分析日志文件
analyze_log() {
local log_file="$1"
local log_name=$(basename "$log_file")

echo -e "${BLUE}分析日志: $log_name${NC}" | tee -a "$OUTPUT_FILE"

# 统计总行数
total_lines=$(wc -l < "$log_file" 2>/dev/null || echo "0")
echo "总行数: $total_lines" | tee -a "$OUTPUT_FILE"

if [ "$total_lines" -eq 0 ]; then
echo "空文件或无法读取" | tee -a "$OUTPUT_FILE"
echo "" | tee -a "$OUTPUT_FILE"
return
fi

# 按日志级别统计
echo "按级别统计:" | tee -a "$OUTPUT_FILE"

for level in "ERROR" "WARN" "WARNING" "INFO" "DEBUG" "FATAL"; do
count=$(grep -c -i "$level" "$log_file" 2>/dev/null || echo "0")
if [ "$count" -gt 0 ]; then
if [ "$level" = "ERROR" ] || [ "$level" = "FATAL" ]; then
if [ "$count" -gt "$ERROR_THRESHOLD" ]; then
echo -e " ${RED}$level: $count${NC}" | tee -a "$OUTPUT_FILE"
else
echo " $level: $count" | tee -a "$OUTPUT_FILE"
fi
elif [ "$level" = "WARN" ] || [ "$level" = "WARNING" ]; then
echo -e " ${YELLOW}$level: $count${NC}" | tee -a "$OUTPUT_FILE"
else
echo " $level: $count" | tee -a "$OUTPUT_FILE"
fi
fi
done

# 最近错误
echo "最近错误:" | tee -a "$OUTPUT_FILE"
grep -i -E "ERROR|FATAL" "$log_file" | tail -5 | while read -r line; do
echo -e " ${RED}$line${NC}" | tee -a "$OUTPUT_FILE"
done

# 时间分布
echo "时间分布 (最近24小时):" | tee -a "$OUTPUT_FILE"

# 尝试提取时间戳并统计
for hour in {00..23}; do
count=$(grep -c "$(date +%Y-%m-%d)T${hour}" "$log_file" 2>/dev/null || echo "0")
if [ "$count" -gt 0 ]; then
printf " %02d:00 - %02d:59: %4d 条\n" "$hour" "$hour" "$count" | tee -a "$OUTPUT_FILE"
fi
done

# 最频繁的IP地址(针对访问日志)
if [[ "$log_name" == *access* ]] || [[ "$log_name" == *http* ]]; then
echo "最频繁访问IP:" | tee -a "$OUTPUT_FILE"
grep -o -E '([0-9]{1,3}\.){3}[0-9]{1,3}' "$log_file" 2>/dev/null | \
sort | uniq -c | sort -rn | head -5 | while read -r count ip; do
echo " $ip: $count 次" | tee -a "$OUTPUT_FILE"
done
fi

echo "" | tee -a "$OUTPUT_FILE"
}

# 主函数
main() {
echo "开始日志分析..." | tee "$OUTPUT_FILE"
echo "时间: $(date)" | tee -a "$OUTPUT_FILE"
echo "日志目录: $LOG_DIR" | tee -a "$OUTPUT_FILE"
echo "输出文件: $OUTPUT_FILE" | tee -a "$OUTPUT_FILE"
echo "=" * 60 | tee -a "$OUTPUT_FILE"
echo "" | tee -a "$OUTPUT_FILE"

# 查找日志文件
log_files=$(find "$LOG_DIR" -name "*.log" -type f -mtime -7 2>/dev/null | head -10)

if [ -z "$log_files" ]; then
echo "未找到日志文件" | tee -a "$OUTPUT_FILE"
return 1
fi

# 分析每个日志文件
for log_file in $log_files; do
if [ -r "$log_file" ]; then
analyze_log "$log_file"
else
echo "无法读取: $log_file" | tee -a "$OUTPUT_FILE"
fi
done

# 生成摘要
echo -e "${GREEN}=== 分析摘要 ===${NC}" | tee -a "$OUTPUT_FILE"
echo "分析完成时间: $(date)" | tee -a "$OUTPUT_FILE"
echo "分析文件数: $(echo "$log_files" | wc -w)" | tee -a "$OUTPUT_FILE"
echo "详细报告: $OUTPUT_FILE" | tee -a "$OUTPUT_FILE"

# 如果有大量错误,发出警告
total_errors=$(grep -c -i "ERROR" "$OUTPUT_FILE")
if [ "$total_errors" -gt "$ERROR_THRESHOLD" ]; then
echo -e "${RED}警告: 发现大量错误 ($total_errors 个)${NC}" | tee -a "$OUTPUT_FILE"
fi

echo -e "${GREEN}分析完成${NC}"
}

# 执行
main "$@"
```

6.3 批量文件处理脚本

```bash
#!/bin/bash
# batch-file-processor.sh

# 配置
INPUT_DIR="./input"
OUTPUT_DIR="./output"
BACKUP_DIR="./backup"
LOG_FILE="./batch_processing_$(date +%Y%m%d_%H%M%S).log"

# 支持的文件类型
SUPPORTED_EXTENSIONS=("txt" "csv" "json" "xml" "log")

# 初始化
init() {
echo "初始化批量文件处理器..."

# 创建必要的目录
mkdir -p "$INPUT_DIR"
mkdir -p "$OUTPUT_DIR"
mkdir -p "$BACKUP_DIR"

# 创建日志文件
> "$LOG_FILE"

log "INFO" "初始化完成"
log "INFO" "输入目录: $INPUT_DIR"
log "INFO" "输出目录: $OUTPUT_DIR"
log "INFO" "备份目录: $BACKUP_DIR"
log "INFO" "日志文件: $LOG_FILE"
}

# 日志函数
log() {
local level="$1"
local message="$2"
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")

case $level in
"ERROR") color="\033[0;31m" ;;
"WARN") color="\033[1;33m" ;;
"INFO") color="\033[0;32m" ;;
"DEBUG") color="\033[0;34m" ;;
*) color="\033[0m" ;;
esac

echo -e "${color}[$timestamp] [$level] $message${NC}"
echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
}

# 检查文件类型
check_file_type() {
local file="$1"
local extension="${file##*.}"

for ext in "${SUPPORTED_EXTENSIONS[@]}"; do
if [[ "$extension" == "$ext" ]]; then
return 0
fi
done

return 1
}

# 处理文本文件
process_text_file() {
local input_file="$1"
local output_file="$2"

log "INFO" "处理文本文件: $(basename "$input_file")"

# 转换为大写
tr 'a-z' 'A-Z' < "$input_file" > "$output_file"

# 统计行数、单词数、字符数
local lines=$(wc -l < "$output_file")
local words=$(wc -w < "$output_file")
local chars=$(wc -m < "$output_file")

echo "文件统计:" >> "$output_file"
echo "==========" >> "$output_file"
echo "行数: $lines" >> "$output_file"
echo "单词数: $words" >> "$output_file"
echo "字符数: $chars" >> "$output_file"

log "INFO" "处理完成: 行数=$lines, 单词数=$words, 字符数=$chars"
}

# 处理CSV文件
process_csv_file() {
local input_file="$1"
local output_file="$2"

log "INFO" "处理CSV文件: $(basename "$input_file")"

# 检查文件是否有标题行
if head -1 "$input_file" | grep -q -E "^[a-zA-Z]"; then
# 有标题行,保留
cp "$input_file" "$output_file"
local total_lines=$(wc -l < "$input_file")
local data_lines=$((total_lines - 1))

# 添加统计信息
echo "" >> "$output_file"
echo "# 统计信息" >> "$output_file"
echo "总行数: $total_lines" >> "$output_file"
echo "数据行数: $data_lines" >> "$output_file"
else
# 无标题行,添加默认标题
echo "col1,col2,col3,col4,col5" > "$output_file"
cat "$input_file" >> "$output_file"
fi

log "INFO" "CSV处理完成"
}

# 处理JSON文件
process_json_file() {
local input_file="$1"
local output_file="$2"

log "INFO" "处理JSON文件: $(basename "$input_file")"

# 使用jq格式化JSON(如果可用)
if command -v jq >/dev/null 2>&1; then
jq '.' "$input_file" > "$output_file" 2>/dev/null
if [ $? -eq 0 ]; then
log "INFO" "使用jq格式化JSON"
else
# jq失败,直接复制
cp "$input_file" "$output_file"
log "WARN" "JSON格式化失败,直接复制文件"
fi
else
cp "$input_file" "$output_file"
log "WARN" "jq未安装,直接复制JSON文件"
fi
}

# 处理XML文件
process_xml_file() {
local input_file="$1"
local output_file="$2"

log "INFO" "处理XML文件: $(basename "$input_file")"

# 使用xmllint格式化XML(如果可用)
if command -v xmllint >/dev/null 2>&1; then
xmllint --format "$input_file" > "$output_file" 2>/dev/null
if [ $? -eq 0 ]; then
log "INFO" "使用xmllint格式化XML"
else
cp "$input_file" "$output_file"
log "WARN" "XML格式化失败,直接复制文件"
fi
else
cp "$input_file" "$output_file"
log "WARN" "xmllint未安装,直接复制XML文件"
fi
}

# 处理日志文件
process_log_file() {
local input_file="$1"
local output_file="$2"

log "INFO" "处理日志文件: $(basename "$input_file")"

# 提取错误和警告
grep -E -i "(error|warn|fail|critical|exception)" "$input_file" > "$output_file"

local error_count=$(grep -c -i "error" "$input_file")
local warn_count=$(grep -c -i "warn" "$input_file")

# 添加摘要
echo "" >> "$output_file"
echo "# 日志摘要" >> "$output_file"
echo "==========" >> "$output_file"
echo "错误数: $error_count" >> "$output_file"
echo "警告数: $warn_count" >> "$output_file"
echo "总行数: $(wc -l < "$input_file")" >> "$output_file"

log "INFO" "日志处理完成: 错误=$error_count, 警告=$warn_count"
}

# 备份文件
backup_file() {
local file="$1"
local backup_path="$BACKUP_DIR/$(basename "$file").$(date +%Y%m%d_%H%M%S).bak"

cp "$file" "$backup_path"
log "INFO" "文件已备份到: $backup_path"
}

# 主处理函数
process_files() {
log "INFO" "开始批量处理文件"

local processed=0
local skipped=0
local failed=0

# 检查输入目录
if [ ! -d "$INPUT_DIR" ]; then
log "ERROR" "输入目录不存在: $INPUT_DIR"
return 1
fi

# 获取输入文件
local files=$(find "$INPUT_DIR" -maxdepth 1 -type f)

if [ -z "$files" ]; then
log "WARN" "输入目录中没有文件"
return 0
fi

# 处理每个文件
for input_file in $files; do
local filename=$(basename "$input_file")
local extension="${filename##*.}"
local output_file="$OUTPUT_DIR/${filename%.*}_processed.${extension}"

log "INFO" "处理文件: $filename"

# 检查文件类型
if ! check_file_type "$filename"; then
log "WARN" "跳过不支持的文件类型: $filename"
((skipped++))
continue
fi

# 备份原始文件
backup_file "$input_file"

# 根据文件类型处理
case $extension in
"txt")
process_text_file "$input_file" "$output_file"
;;
"csv")
process_csv_file "$input_file" "$output_file"
;;
"json")
process_json_file "$input_file" "$output_file"
;;
"xml")
process_xml_file "$input_file" "$output_file"
;;
"log")
process_log_file "$input_file" "$output_file"
;;
*)
log "ERROR" "未知文件类型: $extension"
((failed++))
continue
;;
esac

if [ $? -eq 0 ]; then
log "INFO" "文件处理成功: $filename -> $(basename "$output_file")"
((processed++))
else
log "ERROR" "文件处理失败: $filename"
((failed++))
fi
done

# 输出统计信息
echo ""
log "INFO" "=== 处理统计 ==="
log "INFO" "处理文件数: $processed"
log "INFO" "跳过文件数: $skipped"
log "INFO" "失败文件数: $failed"
log "INFO" "总文件数: $(echo "$files" | wc -w)"

if [ $failed -eq 0 ]; then
log "INFO" "批量处理完成"
return 0
else
log "ERROR" "批量处理完成,但有 $failed 个文件失败"
return 1
fi
}

# 清理函数
cleanup() {
log "INFO" "执行清理..."

# 删除临时文件
find /tmp -name "batch_*" -mtime +7 -delete 2>/dev/null

# 压缩日志文件(如果大于1MB)
local log_size=$(wc -c < "$LOG_FILE" 2>/dev/null || echo 0)
if [ $log_size -gt 1048576 ]; then
gzip "$LOG_FILE"
log "INFO" "日志文件已压缩"
fi
}

# 主函数
main() {
# 设置颜色
NC='\033[0m'

# 显示标题
echo "╔══════════════════════════════════════╗"
echo "║ 批量文件处理器 v1.0 ║"
echo "╚══════════════════════════════════════╝"
echo ""

# 初始化
init

# 处理文件
process_files
local result=$?

# 清理
cleanup

# 显示结果
echo ""
if [ $result -eq 0 ]; then
echo -e "\033[0;32m处理成功完成!\033[0m"
else
echo -e "\033[0;31m处理完成,但有错误发生。\033[0m"
fi

echo "查看日志文件: $LOG_FILE"
echo "输出目录: $OUTPUT_DIR"

return $result
}

# 执行主函数
main "$@"
```

七、Shell 技巧与窍门

7.1 命令行效率技巧

```bash
# 1. 快速导航
cd - # 返回上一个目录
cd ~ # 返回家目录
cd .. # 上级目录
pushd /tmp # 保存当前目录并切换
popd # 返回保存的目录

# 2. 命令历史
history # 查看历史命令
!! # 上一条命令
!$ # 上条命令的最后一个参数
!string # 执行最近以string开头的命令
ctrl+r # 搜索历史命令
ctrl+p / ctrl+n # 历史命令上/下
ctrl+a / ctrl+e # 移动到行首/行尾
ctrl+u / ctrl+k # 删除到行首/行尾
ctrl+w / alt+d # 删除前/后一个单词

# 3. 命令别名
alias ll='ls -la' # 创建别名
alias grep='grep --color=auto' # 带颜色的grep
alias rm='rm -i' # 交互式删除
unalias ll # 删除别名

# 4. 命令补全
tab # 自动补全命令/文件名
tab tab # 显示所有可能选项

# 5. 进程管理
ctrl+z # 暂停当前进程
bg # 后台继续
fg # 前台继续
jobs # 查看后台作业
kill %1 # 终止作业1
disown # 分离作业
nohup command & # 退出终端后继续运行
```

7.2 高级技巧

```bash
# 1. 花括号扩展
echo file{1..10}.txt # file1.txt file2.txt ... file10.txt
echo {a..z} # a b c ... z
mkdir -p dir{1..5}/sub{1..3} # 创建嵌套目录
cp file.txt{,.bak} # 复制为file.txt.bak

# 2. 进程替换
diff <(ls dir1) <(ls dir2) # 比较两个目录
cat <(echo "hello") <(echo "world")

# 3. 并行执行
parallel echo ::: A B C # 并行执行(需要安装parallel)
for i in {1..10}; do
(command $i &) # 后台并行
done
wait # 等待所有后台进程

# 4. 网络技巧
ssh user@host "command" # 远程执行命令
rsync -avz source/ user@host:dest/ # 同步文件
scp file.txt user@host:/path/ # 安全复制

# 5. 数据操作
jq . file.json # 格式化JSON(需要安装jq)
yq . file.yaml # 处理YAML
csvtool readable file.csv # 格式化CSV
xmlstarlet sel -t -v "//node" file.xml # 处理XML

# 6. 监控与调试
watch -n 1 "command" # 每秒执行一次命令
time command # 测量命令执行时间
strace -f command # 跟踪系统调用
ltrace command # 跟踪库调用
```

7.3 Shell 配置优化

```bash
# ~/.bashrc 优化配置示例

# 历史记录配置
export HISTSIZE=10000 # 内存中历史记录数
export HISTFILESIZE=20000 # 历史文件记录数
export HISTCONTROL=ignoreboth # 忽略重复命令和空格开头命令
export HISTTIMEFORMAT="%F %T " # 历史记录时间戳
shopt -s histappend # 追加而不是覆盖历史文件

# 命令行编辑
set -o vi # 使用vi编辑模式
# 或
set -o emacs # 使用emacs编辑模式

# 补全配置
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi

# 颜色支持
export TERM=xterm-256color
export CLICOLOR=1
export LSCOLORS=ExFxBxDxCxegedabagacad

# 别名
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# 提示符定制
export PS1="\[\033[38;5;11m\]\u\[$(tput sgr0)\]@\[\033[38;5;13m\]\h\[$(tput sgr0)\]:\[\033[38;5;14m\]\w\[$(tput sgr0)\]\\$ "

# 路径优化
export PATH="$HOME/bin:$PATH"
export PATH="$PATH:/usr/local/bin"
export PATH="$PATH:/snap/bin"

# 编辑器设置
export EDITOR=vim
export VISUAL=vim

# 语言设置
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# 安全设置
umask 022 # 默认文件权限

# 自定义函数
# 快速进入目录并列出文件
cdl() {
cd "$@" && ls -la
}

# 创建目录并进入
mkcd() {
mkdir -p "$1" && cd "$1"
}

# 查找文件并统计
findcount() {
find . -type f -name "*$1*" | wc -l
}

# 显示当前目录大小
ds() {
du -sh ./*
}

# 提取压缩文件
extract() {
if [ -f "$1" ]; then
case "$1" in
*.tar.bz2) tar xjf "$1" ;;
*.tar.gz) tar xzf "$1" ;;
*.bz2) bunzip2 "$1" ;;
*.rar) unrar x "$1" ;;
*.gz) gunzip "$1" ;;
*.tar) tar xf "$1" ;;
*.tbz2) tar xjf "$1" ;;
*.tgz) tar xzf "$1" ;;
*.zip) unzip "$1" ;;
*.Z) uncompress "$1" ;;
*.7z) 7z x "$1" ;;
*) echo "'$1' cannot be extracted via extract()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
```

八、故障排除与调试

8.1 常见错误解决

```bash
# 1. 权限错误
# 错误:Permission denied
chmod +x script.sh # 添加执行权限
sudo command # 使用sudo执行
chown user:group file # 修改文件所有者

# 2. 命令未找到
# 错误:command not found
which command # 查找命令位置
whereis command # 查找命令
command -v command # 检查命令是否存在
echo $PATH # 检查PATH变量
export PATH=$PATH:/new/path # 添加路径到PATH

# 3. 语法错误
# 错误:syntax error near unexpected token
bash -n script.sh # 检查语法错误
bash -x script.sh # 调试执行
set -u # 遇到未定义变量时报错

# 4. 文件不存在
# 错误:No such file or directory
ls -la /path # 检查路径是否存在
file /path/to/file # 检查文件类型
readlink -f /path # 获取绝对路径

# 5. 磁盘空间不足
# 错误:No space left on device
df -h # 查看磁盘使用情况
du -sh * # 查看目录大小
find / -type f -size +100M # 查找大文件
```

8.2 调试技巧

```bash
# 1. 详细输出
set -x # 开启调试模式
set +x # 关闭调试模式
bash -x script.sh # 调试整个脚本

# 2. 变量跟踪
declare -p variable # 显示变量属性和值
typeset -p variable # 同上
echo "Variable: $variable" # 打印变量值
printf "Value: %s\n" "$variable"

# 3. 函数调试
declare -f function_name # 显示函数定义
typeset -f function_name # 同上
trap 'echo "Line: $LINENO, Variable: $variable"' DEBUG # 调试钩子

# 4. 性能分析
time command # 测量命令执行时间
/usr/bin/time -v command # 详细资源使用
strace -c command # 系统调用统计

# 5. 错误处理
set -e # 遇到错误立即退出
set -o pipefail # 管道中任何错误都返回失败
trap 'echo "Error at line $LINENO"' ERR # 错误时执行命令
```

九、Shell 安全最佳实践

9.1 安全脚本编写

```bash
#!/bin/bash
# secure-script.sh

# 1. 使用严格模式
set -euo pipefail # 严格模式
set -o noclobber # 防止重定向覆盖
shopt -s failglob # 通配符失败时报错

# 2. 检查输入
if [ $# -eq 0 ]; then
echo "Usage: $0 <argument>" >&2
exit 1
fi

# 3. 验证用户输入
input="$1"
if [[ ! "$input" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Invalid input" >&2
exit 1
fi

# 4. 安全的变量使用
safe_var="${1:-default}" # 使用默认值
quoted_var="$(printf '%q' "$input")" # 安全引用

# 5. 安全的文件操作
tmpfile=$(mktemp /tmp/script.XXXXXX)
trap 'rm -f "$tmpfile"' EXIT # 退出时清理

# 6. 检查命令是否存在
check_command() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "Error: $1 not found" >&2
exit 1
fi
}

# 7. 限制权限
if [ "$EUID" -ne 0 ]; then
echo "Please run as root" >&2
exit 1
fi

# 8. 安全日志
log() {
local level="$1"
local message="$2"
logger -t "$(basename "$0")" "[$level] $message"
}

# 9. 清理敏感信息
cleanup() {
shred -u "$tmpfile"
history -c
}

trap cleanup EXIT
```

十、Shell 学习资源

10.1 在线资源

· 官方文档:
· GNU Bash Manual: https://www.gnu.org/software/bash/manual/
· Advanced Bash-Scripting Guide: https://tldp.org/LDP/abs/html/
· 教程与指南:
· Bash Academy: https://guide.bash.academy/
· ShellCheck (在线检查): https://www.shellcheck.net/
· Explain Shell (命令解释): https://explainshell.com/
· 社区与论坛:
· Stack Overflow Bash tag
· Reddit: r/bash, r/commandline
· Unix & Linux Stack Exchange

10.2 推荐书籍

· The Linux Command Line by William Shotts
· Bash Cookbook by Carl Albing and JP Vossen
· Classic Shell Scripting by Arnold Robbins and Nelson Beebe
· Learning the bash Shell by Cameron Newham

10.3 练习平台

· OverTheWire: Bandit wargame (Linux命令行练习)
· HackerRank: Shell domain
· Codewars: Bash scripting challenges
· LeetCode: Shell problems

---

快速参考手册

常用命令速查表

类别 命令 用途
文件操作 ls, cd, cp, mv, rm 文件管理
文本处理 cat, grep, sed, awk, sort 文本操作
系统信息 ps, top, df, free, uname 系统监控
网络 ping, curl, wget, ssh, netstat 网络操作
用户权限 chmod, chown, sudo, su 权限管理
压缩 tar, gzip, zip, unzip 文件压缩
查找 find, locate, which, whereis 文件查找
进程 kill, pkill, jobs, bg, fg 进程控制

Shell 脚本速查

```bash
#!/bin/bash # Shebang
# 注释 # 单行注释
: '多行注释' # 多行注释

# 变量
var="value" # 变量赋值
echo "$var" # 变量使用

# 条件判断
if [ condition ]; then
commands
fi

# 循环
for i in list; do
commands
done

while condition; do
commands
done

# 函数
function_name() {
commands
}

# 数组
arr=(value1 value2) # 数组定义
echo "${arr[0]}" # 访问元素

# 参数
$0, $1, $@, $# # 位置参数

# 退出状态
exit 0 # 成功退出
exit 1 # 失败退出
```

快捷键速查

快捷键 功能
Ctrl+A 移动到行首
Ctrl+E 移动到行尾
Ctrl+U 删除到行首
Ctrl+K 删除到行尾
Ctrl+W 删除前一个单词
Ctrl+R 搜索历史命令
Tab 命令补全
Ctrl+C 终止命令
Ctrl+Z 暂停命令
Ctrl+D 退出Shell

---

总结

Shell 是 Linux/Unix 系统的核心工具,掌握它可以:

1. 高效管理系统:通过命令行快速完成各种任务
2. 自动化工作流:编写脚本批量处理重复性工作
3. 深入理解系统:了解操作系统的工作原理
4. 提升工作效率:使用快捷键和技巧提高操作速度

学习建议:

· 从基础命令开始,逐步深入
· 多动手实践,解决实际问题
· 阅读优秀的脚本代码,学习最佳实践
· 使用 ShellCheck 检查脚本语法
· 参与开源项目,积累实战经验

Shell 不仅是系统管理员的必备技能,也是开发者、数据分析师等技术人员的重要工具。随着 DevOps 和云原生技术的发展,Shell 的重要性更加凸显。

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-02-09 09:00:47 HTTP/2.0 GET : https://f.mffb.com.cn/a/460228.html
  2. 运行时间 : 0.337506s [ 吞吐率:2.96req/s ] 内存消耗:4,655.79kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=6969af1da55cef3e020b8cab4905124d
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000476s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000624s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.010625s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.003760s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000660s ]
  6. SELECT * FROM `set` [ RunTime:0.003751s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000639s ]
  8. SELECT * FROM `article` WHERE `id` = 460228 LIMIT 1 [ RunTime:0.013880s ]
  9. UPDATE `article` SET `lasttime` = 1770598847 WHERE `id` = 460228 [ RunTime:0.003589s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 67 LIMIT 1 [ RunTime:0.001139s ]
  11. SELECT * FROM `article` WHERE `id` < 460228 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.004113s ]
  12. SELECT * FROM `article` WHERE `id` > 460228 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.033164s ]
  13. SELECT * FROM `article` WHERE `id` < 460228 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.103061s ]
  14. SELECT * FROM `article` WHERE `id` < 460228 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.077218s ]
  15. SELECT * FROM `article` WHERE `id` < 460228 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.011221s ]
0.339044s