摘要: 作为Linux系统管理员或开发者,掌握高效的命令行操作技巧能让你的工作效率提升数倍。本文整理了20个最实用的Linux命令行技巧,从基础到进阶,助你成为真正的Linux高手!
引言
在Linux的世界里,命令行就是你的武器。熟练掌握命令行不仅能让你在工作中游刃有余,还能在关键时刻快速解决问题。本文将分享20个经过实战验证的命令行技巧,涵盖了文件操作、系统监控、网络调试、Shell脚本等多个方面。
一、文件操作高级技巧
1. rsync同步大文件时显示进度条
传统的cp命令在复制大文件时无法显示进度,而rsync可以完美解决这个问题:

# 基本用法:显示进度条 rsync -av --progress source_file destination_file # 同步整个目录并显示详细进度 rsync -avz --progress /source/directory/ /destination/directory/ # 参数说明: # -a: 归档模式,保持文件属性 # -v: 详细输出 # -z: 压缩传输(适用于网络传输) # --progress: 显示进度条
2. find命令结合xargs批量处理文件
find命令配合xargs可以高效地批量处理文件:
# 批量删除30天前的日志文件
find /var/log -name "*.log" -mtime +30 -print0 | xargs -0 rm -f
# 批量修改文件权限
find /home/user/documents -type f -name "*.sh" -print0 | xargs -0 chmod +x
# 批量压缩图片文件
find /images -name "*.jpg" -print0 | xargs -0 -I {} convert {} -quality 80 {}
# 使用-print0和-0参数可以正确处理包含空格的文件名
3. tar压缩时排除特定目录
在打包时排除不需要的目录可以节省大量空间:
# 排除单个目录 tar --exclude='./node_modules' -czf backup.tar.gz . # 排除多个目录 tar --exclude='./node_modules' --exclude='./.git' --exclude='./logs' -czf backup.tar.gz . # 使用排除文件列表 echo "node_modules" > exclude.txt echo ".git" >> exclude.txt echo "logs" >> exclude.txt tar --exclude-from=exclude.txt -czf backup.tar.gz .
二、系统监控与性能分析
4. htop替代传统top命令
htop提供了比top更友好的界面和更多功能:
# 安装htop(Ubuntu/Debian) sudo apt install htop # 安装htop(CentOS/RHEL) sudo yum install htop # 主要功能: # - 颜色编码的进程列表 # - 树状视图显示进程关系 # - 鼠标支持(在终端中) # - 可排序的列 # - 搜索功能
5. iotop监控磁盘I/O性能
当系统变慢时,可能是磁盘I/O瓶颈:
# 安装iotop sudo apt install iotop # Ubuntu/Debian sudo yum install iotop # CentOS/RHEL # 实时监控磁盘I/O sudo iotop # 只显示有I/O活动的进程 sudo iotop -o # 按I/O速率排序 sudo iotop -o -b -n 1
6. netstat和ss网络连接分析对比
现代Linux系统推荐使用ss替代netstat:
# 查看所有监听端口(netstat) netstat -tuln # 查看所有监听端口(ss)- 更快更高效 ss -tuln # 查看进程对应的连接 ss -tulnp # 查看TCP连接状态统计 ss -s # 查看特定端口的连接 ss -tnlp | grep :80
三、Shell脚本优化
7. 错误处理的最佳实践
健壮的Shell脚本必须包含完善的错误处理:
#!/bin/bash
# 设置严格模式
set -euo pipefail
# 自定义错误处理函数
error_handler() {
local line_number=$1
local exit_code=$2
echo "Error on line $line_number with exit code $exit_code"
exit $exit_code
}
# 捕获错误
trap 'error_handler ${LINENO} $?' ERR
# 安全的变量引用
safe_variable="${MY_VAR:-default_value}"
# 检查命令是否存在
command_exists() {
command -v "$1" >/dev/null 2>&1
}
if ! command_exists docker; then
echo "Docker is not installed"
exit 1
fi
8. 函数库的创建和调用
将常用功能封装成函数库:
# 创建functions.sh
#!/bin/bash
# 日志函数
log_info() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $1"
}
log_error() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" >&2
}
# 文件操作函数
backup_file() {
local file="$1"
local backup="${file}.bak.$(date +%s)"
cp "$file" "$backup"
log_info "Backup created: $backup"
}
# 在主脚本中调用
# source ./functions.sh
# log_info "Starting backup process"
# backup_file "/etc/nginx/nginx.conf"
9. 并行处理提升脚本执行速度
利用并行处理加速耗时任务:
#!/bin/bash
# 串行处理(慢)
for host in server1 server2 server3 server4; do
ssh "$host" "uptime"
done
# 并行处理(快)
run_parallel() {
local host="$1"
ssh "$host" "uptime"
}
for host in server1 server2 server3 server4; do
run_parallel "$host" &
done
wait # 等待所有后台任务完成
# 使用GNU Parallel(更高级)
# parallel ssh {} uptime ::: server1 server2 server3 server4
四、网络调试技巧
10. tcpdump抓包分析实战
tcpdump是网络故障排查的利器:
# 基本抓包 sudo tcpdump -i eth0 # 抓取特定主机的流量 sudo tcpdump host 192.168.1.100 # 抓取特定端口的流量 sudo tcpdump port 80 # 抓取HTTP流量 sudo tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' # 保存抓包到文件 sudo tcpdump -w capture.pcap # 从文件读取抓包数据 tcpdump -r capture.pcap
11. mtr结合ping和traceroute
mtr结合了ping和traceroute的功能:
# 安装mtr sudo apt install mtr # Ubuntu/Debian sudo yum install mtr # CentOS/RHEL # 基本使用 mtr google.com # 报告模式(适合脚本使用) mtr --report google.com # 指定协议(ICMP/UDP/TCP) mtr --tcp --port 443 google.com # 限制跳数 mtr -m 10 google.com
12. curl和wget的高级用法
curl高级用法:
# 测试API响应时间
curl -w "@curl-format.txt" -o /dev/null -s https://api.example.com
# curl-format.txt内容:
# time_namelookup: %{time_namelookup}n
# time_connect: %{time_connect}n
# time_appconnect: %{time_appconnect}n
# time_pretransfer: %{time_pretransfer}n
# time_redirect: %{time_redirect}n
# time_starttransfer: %{time_starttransfer}n
# ----------n
# time_total: %{time_total}n
# 上传文件
curl -F "file=@/path/to/file.jpg" https://upload.example.com
# 处理Cookie
curl -c cookies.txt -b cookies.txt https://example.com
wget高级用法:
# 断点续传 wget -c http://example.com/largefile.zip # 递归下载网站 wget --recursive --no-parent --page-requisites --html-extension --convert-links http://example.com # 限制下载速度 wget --limit-rate=100k http://example.com/file.zip # 批量下载 wget -i urls.txt
五、系统管理技巧
13. journalctl日志管理
现代Linux系统使用systemd,日志管理变得简单:
# 查看系统日志 sudo journalctl # 查看特定服务的日志 sudo journalctl -u nginx # 实时跟踪日志 sudo journalctl -u nginx -f # 查看最近的日志 sudo journalctl --since "1 hour ago" # 导出日志到文件 sudo journalctl -u nginx --since "2026-02-14" > nginx.log
14. systemd服务管理
创建和管理自定义systemd服务:
# /etc/systemd/system/myapp.service [Unit] Description=My Application After=network.target [Service] Type=simple User=myuser WorkingDirectory=/opt/myapp ExecStart=/opt/myapp/app.sh Restart=always RestartSec=10 [Install] WantedBy=multi-user.target # 重载systemd配置 sudo systemctl daemon-reload # 启动服务 sudo systemctl start myapp # 设置开机自启 sudo systemctl enable myapp # 查看服务状态 sudo systemctl status myapp
15. 磁盘空间分析
快速找出占用空间大的文件和目录:
# 查看磁盘使用情况
df -h
# 查看目录大小
du -sh /var/log/*
# 找出最大的10个文件
find / -type f -exec du -h {} + 2>/dev/null | sort -hr | head -10
# 使用ncdu进行交互式分析
sudo apt install ncdu
ncdu /
六、安全相关技巧
16. SSH密钥管理
安全的SSH密钥管理实践:
# 生成新的SSH密钥对 ssh-keygen -t ed25519 -C "your_email@example.com" # 添加密钥到ssh-agent eval $(ssh-agent -s) ssh-add ~/.ssh/id_ed25519 # 复制公钥到远程服务器 ssh-copy-id user@remote-server # SSH配置文件优化 (~/.ssh/config) Host myserver HostName 192.168.1.100 User admin IdentityFile ~/.ssh/id_ed25519 Port 2222 ServerAliveInterval 60
17. 文件完整性检查
监控重要文件的完整性:
# 使用sha256sum生成校验和 sha256sum /etc/passwd > passwd.checksum # 验证文件完整性 sha256sum -c passwd.checksum # 使用AIDE进行高级完整性监控 sudo apt install aide sudo aideinit sudo aide --check
18. 用户和权限管理
批量用户管理和权限设置:
# 批量创建用户 for user in alice bob charlie; do sudo useradd -m -s /bin/bash "$user" echo "$user:temp_password" | sudo chpasswd done # 批量修改文件所有权 sudo chown -R www-data:www-data /var/www/html # 查找具有SUID权限的文件 find / -perm -4000 -type f 2>/dev/null # 查找世界可写的文件 find / -perm -o+w -type f 2>/dev/null
七、自动化和调度
19. crontab高级用法
编写健壮的cron任务:
# 编辑crontab crontab -e # 示例:每天凌晨2点备份数据库 0 2 * * * /usr/local/bin/backup-db.sh >> /var/log/backup.log 2>&1 # 示例:每5分钟检查服务状态 */5 * * * * /usr/local/bin/check-service.sh # 环境变量设置 MAILTO=admin@example.com PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # 避免邮件通知 */5 * * * * /usr/local/bin/script.sh >/dev/null 2>&1
20. at命令一次性任务调度
使用at命令调度一次性任务:
# 安装at(如果未安装) sudo apt install at # Ubuntu/Debian sudo yum install at # CentOS/RHEL # 启动at服务 sudo systemctl enable --now atd # 调度任务 echo "systemctl restart nginx" | at 2:00 AM tomorrow # 查看待执行任务 atq # 删除任务 atrm <job_number>
结语
这20个命令行技巧涵盖了Linux系统运维的各个方面。掌握这些技巧不仅能提高你的工作效率,还能帮助你在紧急情况下快速定位和解决问题。记住,真正的Linux高手不是记住所有命令的人,而是知道如何快速找到解决方案的人。
