开篇:当你的Shell技能遇到瓶颈
你是否经常:
今天我要给你一套Shell效率工具包,让你的命令行体验从"石器时代"直接跃迁到"智能时代"!
# 提取JSON字段值
echo '{"name":"Alice","age":25}' | jq '.name' # 输出:"Alice"
# 过滤数组元素
curl -s https://api.github.com/repos/stedolan/jq/issues | \
jq '.[] | select(.state == "open") | .title'
# 数组→CSV转换
jq -r '.users[] | [.name, .age] | @csv' data.json
# 多文件合并
jq -s '.[0].users + .[1].users' file1.json file2.json
# 动态键名处理
echo '{"user-1": {"name": "Bob"}}' | jq '.["user-1"].name'
# 统计各日志级别的数量
cat app.log | jq -r '.level' | sort | uniq -c | \
awk '{printf "%-8s %d次\n", $2, $1}'
# 显示完整请求过程(-v)
curl -v https://api.example.com
# 只显示响应头(-I)
curl -I https://example.com
# 输出耗时明细(--trace-time)
curl --trace-time -o /dev/null -s https://example.com
# 伪装浏览器请求
curl -H "User-Agent: Mozilla/5.0" -H "Accept-Language: en-US" https://example.com
# 处理Cookie会话
curl -c cookies.txt -b cookies.txt -d "user=admin&pass=123" https://example.com/login
# 文件分段下载(断点续传)
curl -C - -O http://example.com/bigfile.zip
check_api() {
local url=$1
http_code=$(curl -s -o /dev/null -w "%{http_code}" "$url")
[ "$http_code" -eq 200 ] && \
echo "✅ $url 健康" || \
echo "❌ $url 异常 (状态码: $http_code)"
}
# 并行处理文件(替代for循环)
ls *.log | parallel -j 4 "grep 'ERROR' {} > {}.errors"
# 多参数并行(神奇的三冒号)
parallel -j 8 "curl -s http://example.com/api?q={1}&page={2}" ::: A B C ::: 1 2 3
# 串行处理
time for i in {1..10}; do sleep 1; done # 真实时间≈10s
# 并行处理(4线程)
time parallel -j 4 "sleep 1" ::: {1..10} # 真实时间≈3s
# 将JPG转为PNG(使用所有CPU核心)
find . -name "*.jpg" | parallel --bar convert {} {.}.png
#!/bin/bash
# 保存到 ~/.bash_cheatsheet
cheat() {
case $1 in
network)
cat <<EOF
# 查看监听端口
sudo lsof -i -P -n | grep LISTEN
# 测试带宽
iperf3 -c 192.168.1.1
EOF
;;
*)
echo "可用分类:"
grep -oP '^\s+\w+\)' ~/.bash_cheatsheet | tr -d ')'
;;
esac
}
# 使用fzf交互选择历史命令
bind '"\C-r": "\C-x \C-u $(\history | fzf +s +m | sed \"s/ *[0-9]* *//\")\e\C-e\er\C-m"'
# 快速目录跳转(z.lua)
z() { _zlua "$@" && cd "$(pwd -P)"; }
# 安装regex101命令行版(需npm)
npm install -g regex101-cli
# 解析正则表达式
regex101 explain '^(?[^@]+)@(?.+)$'
# 使用time观察耗时
time ./your_script.sh
# 详细性能分析(bash自带)
set -x; PS4='+ $EPOCHREALTIME '; your_script.sh
#!/bin/bash
# monitor.sh - 系统监控仪表盘
# 并行获取数据(使用临时文件避免竞态)
temp_dir=$(mktemp -d)
parallel ::: \
"free -m > $temp_dir/mem" \
"df -h > $temp_dir/disk" \
"uptime > $temp_dir/cpu"
# 用jq生成JSON报告
{
echo '{'
echo '"memory": {'
awk '/Mem:/ {printf "\"total\": %s, \"used\": %s", $2, $3}' $temp_dir/mem
echo '},'
echo '"disk": {'
df -h / | awk 'NR==2 {printf "\"total\": \"%s\", \"used\": \"%s\"", $2, $3}'
echo '}'
echo '}'
} | jq . | tee report.json
# 清理临时文件
rm -rf "$temp_dir"
需求:
奖励功能: