Shell 脚本与常用命令
一、常用命令速查
1. 文件与目录
ls -lh # 列表
cd /path
pwd
mkdir -p a/b/c
rm -rf dir
cp -r src dst
mv src dst
find . -name "*.c" -type f
locate / grep / ag / rg
ln -s target link # 软链接
ln target link # 硬链接
stat file
file file
basename / dirname
2. 文本查看
cat / less / more
head -n 10
tail -n 10 -f # -f 实时跟踪
tac # 反序
nl # 带行号
od -x / hexdump
xxd
3. 文本处理
grep -rn "pattern" .
grep -E "reg(ex|exp)" file
sed -i 's/old/new/g' file
sed -n '10,20p' file
awk '{print $1, $3}' file
awk -F: '{print $1}' /etc/passwd
cut -d: -f1
sort / uniq / wc
tr 'a-z' 'A-Z'
xargs
column -t
4. 权限与用户
chmod 755 file # rwxr-xr-x
chown user:group file
chmod u+s file # SUID
id
whoami
su / sudo
5. 系统状态
uname -a
cat /proc/cpuinfo
cat /proc/meminfo
free -h
uptime
top / htop / atop
ps aux / ps -ef
pstree
vmstat 1
iostat 1
mpstat 1
lsof
fuser
dmesg
6. 进程管理
kill PID
kill -9 PID # SIGKILL
killall proc
pkill pattern
nice / renice
bg / fg / jobs
nohup cmd &
disown
7. 网络
ifconfig / ip addr
ip route
netstat -tulnp / ss -tulnp
ping / traceroute / mtr
curl / wget
nc / socat
nmap
tcpdump
iptables
8. 磁盘
df -h
du -sh *
mount / umount
fdisk / parted
mkfs.ext4 / mkfs.vfat
fsck
lsblk
blkid
9. 包管理
# Debian/Ubuntu (主机)
apt update && apt install xxx
# Arch
pacman -S xxx
# Buildroot / Yocto 自带包管理
opkg install xxx # OpenWrt
rpm / dpkg # 通用
10. 压缩
tar -czvf a.tar.gz dir/
tar -xzvf a.tar.gz
tar -cjf a.tar.bz2
zip / unzip
gzip / bzip2 / xz
7z
二、Shell 脚本基础
1. Shebang
#!/bin/bash
#!/bin/sh
#!/usr/bin/env bash
2. 变量
NAME=value # 注意无空格
echo $NAME
echo "${NAME}_end"
readonly PI=3.14
local x=1 # 函数内
export PATH=$PATH:/opt/bin
3. 引用
"$var" # 不分割、不通配
'$var' # 不展开
`cmd` # 命令替换(老)
$(cmd) # 推荐
4. 条件
if [ -f file ]; then
:
elif [[ "$var" =~ ^[0-9]+$ ]]; then
:
else
:
fi
# 文件测试
[ -f file ] [ -d dir ] [ -e exists ]
[ -r file ] [ -w file ] [ -x file ]
[ -z "$s" ] [ -n "$s" ]
# 字符串
[ "$a" = "$b" ] [ "$a" != "$b" ]
# 整数(不要用 [],会字符串比较)
[ "$a" -eq "$b" ] -eq/-ne/-lt/-gt/-le/-ge
# 逻辑
[ cond1 ] && [ cond2 ]
[[ cond1 && cond2 ]]
5. 循环
for i in 1 2 3; do echo $i; done
for i in $(seq 1 10); do :; done
for f in *.c; do :; done
for ((i=0; i<10; i++)); do :; done
while read line; do echo "$line"; done < file
until cmd; do :; done
6. 函数
my_func() {
local arg=$1
echo "$arg"
return 0
}
my_func hello
echo $? # 上一个返回值
7. 数组
arr=(a b c)
arr+=(d)
echo "${arr[0]}" "${arr[@]}" "${#arr[@]}"
for x in "${arr[@]}"; do echo "$x"; done
8. 关联数组(Bash 4+)
declare -A map
map[foo]=bar
echo "${map[foo]}"
9. 常用惯用法
# 安全模式
set -euo pipefail
IFS=$'\n\t'
# 错误处理
trap 'echo "Error on line $LINENO"' ERR
trap 'cleanup' EXIT
# 临时文件
tmp=$(mktemp)
trap "rm -f $tmp" EXIT
# 参数
while getopts "ab:c" opt; do
case $opt in
a) A=1 ;;
b) B=$OPTARG ;;
c) C=1 ;;
*) usage ;;
esac
done
# 调试
set -x
bash -x script.sh
10. 嵌入式常用脚本片段
# 监控进程
while true; do
if ! pgrep myapp > /dev/null; then
logger "myapp crashed, restarting..."
/usr/bin/myapp &
fi
sleep 5
done
# 同步文件
rsync -av --delete src/ user@host:/dest/
# 从串口抓日志
stty -F /dev/ttyS0 115200 raw -echo
cat /dev/ttyS0 | tee -a logfile