1. fzf - 模糊查找神器
1.1 安装与配置
创建安装脚本:install_fzf.sh
bash
#!/bin/bash
# fzf 模糊查找工具安装脚本
set -e
echo "=== 开始安装 fzf ==="
# 方法1: 使用包管理器安装
if command -v apt-get &> /dev/null; then
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y fzf
elif command -v yum &> /dev/null; then
# CentOS/RHEL
sudo yum install -y epel-release
sudo yum install -y fzf
elif command -v brew &> /dev/null; then
# macOS
brew install fzf
else
# 方法2: 从源码安装
echo "使用源码安装 fzf..."
git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
~/.fzf/install --all
fi
# 验证安装
if command -v fzf &> /dev/null; then
echo "✅ fzf 安装成功"
fzf --version
else
echo "❌ fzf 安装失败"
exit 1
fi
# 创建配置文件
echo "配置 fzf..."
mkdir -p ~/.config/fzf
cat > ~/.config/fzf/fzf.sh << 'EOF'
#!/bin/bash
# fzf 配置
export FZF_DEFAULT_OPTS="
--height 40%
--layout=reverse
--border
--preview 'bat --color=always {} 2>/dev/null || cat {} 2>/dev/null'
--preview-window right:60%
--color=fg:#f8f8f2,bg:#282a36,hl:#bd93f9
--color=fg+:#f8f8f2,bg+:#44475a,hl+:#bd93f9
--color=info:#ffb86c,prompt:#50fa7b,pointer:#ff79c6
--color=marker:#ff79c6,spinner:#ffb86c,header:#6272a4"
# 使用 fd 作为默认搜索命令(如果已安装)
if command -v fd > /dev/null; then
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
fi
# 目录搜索
export FZF_ALT_C_COMMAND="fd --type d --hidden --follow --exclude .git"
# 键绑定
source ~/.fzf/shell/key-bindings.bash 2>/dev/null || true
source ~/.fzf/shell/completion.bash 2>/dev/null || true
EOF
# 添加到 bashrc
echo "source ~/.config/fzf/fzf.sh" >> ~/.bashrc
echo "=== fzf 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
1.2 高级使用技巧
创建 fzf 实用脚本:fzf_helpers.sh
bash
#!/bin/bash
# fzf 高级使用技巧集合
# 1. 快速文件搜索和编辑
fzf_edit() {
local file
file=$(fzf --query="$1" --select-1 --exit-0)
[ -n "$file" ] && ${EDITOR:-vim} "$file"
}
# 2. 目录快速跳转
fzf_cd() {
local dir
dir=$(find ${1:-.} -type d 2>/dev/null | fzf +m) &&
cd "$dir"
}
# 3. 进程搜索和杀死
fzf_kill() {
local pid
pid=$(ps -ef | sed 1d | fzf -m | awk '{print $2}')
if [ -n "$pid" ]; then
echo "$pid" | xargs kill -9
echo "进程已终止"
fi
}
# 4. Git 分支选择
fzf_git_checkout() {
local branch
branch=$(git branch -a | fzf | sed 's/^[* ]*//' | sed 's#remotes/[^/]*/##')
[ -n "$branch" ] && git checkout "$branch"
}
# 5. 历史命令搜索
fzf_history() {
local command
command=$(history | fzf +s | sed 's/ *[0-9]* *//')
[ -n "$command" ] && eval "$command"
}
# 6. SSH 主机连接
fzf_ssh() {
local host
host=$(grep -E '^Host\s+' ~/.ssh/config 2>/dev/null | awk '{print $2}' | fzf)
[ -n "$host" ] && ssh "$host"
}
# 7. Docker 容器管理
fzf_docker() {
local container
case "$1" in
"exec")
container=$(docker ps | sed 1d | fzf | awk '{print $1}')
[ -n "$container" ] && docker exec -it "$container" bash
;;
"logs")
container=$(docker ps | sed 1d | fzf | awk '{print $1}')
[ -n "$container" ] && docker logs -f "$container"
;;
"stop")
container=$(docker ps | sed 1d | fzf | awk '{print $1}')
[ -n "$container" ] && docker stop "$container"
;;
*)
echo "用法: fzf_docker {exec|logs|stop}"
;;
esac
}
# 8. 文件内容搜索
fzf_grep() {
local pattern file
pattern=$1
file=$(fzf --query="$pattern" --select-1 --exit-0)
[ -n "$file" ] && grep -n "$pattern" "$file"
}
# 显示使用帮助
fzf_help() {
cat << 'EOF'
fzf 高级命令速查:
fzf_edit - 搜索并编辑文件
fzf_cd - 搜索并跳转目录
fzf_kill - 搜索并杀死进程
fzf_git_checkout - 搜索并切换 Git 分支
fzf_history - 搜索并执行历史命令
fzf_ssh - 搜索并连接 SSH 主机
fzf_docker - Docker 容器管理
fzf_grep - 搜索文件内容
快捷键:
Ctrl+R - 搜索历史命令
Ctrl+T - 搜索文件
Alt+C - 搜索目录
EOF
}
# 如果直接执行脚本,显示帮助
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
fzf_help
fi
2. bat - 语法高亮的 cat
2.1 安装与配置
创建安装脚本:install_bat.sh
bash
#!/bin/bash
# bat 安装脚本
set -e
echo "=== 开始安装 bat ==="
# 检测系统并安装
if command -v apt-get &> /dev/null; then
# Ubuntu/Debian
wget https://github.com/sharkdp/bat/releases/download/v0.18.3/bat_0.18.3_amd64.deb
sudo dpkg -i bat_0.18.3_amd64.deb
rm bat_0.18.3_amd64.deb
elif command -v yum &> /dev/null; then
# CentOS/RHEL
wget https://github.com/sharkdp/bat/releases/download/v0.18.3/bat-v0.18.3-x86_64-unknown-linux-gnu.tar.gz
tar -xzf bat-v0.18.3-x86_64-unknown-linux-gnu.tar.gz
sudo cp bat-v0.18.3-x86_64-unknown-linux-gnu/bat /usr/local/bin/
rm -rf bat-v0.18.3-x86_64-unknown-linux-gnu*
elif command -v brew &> /dev/null; then
# macOS
brew install bat
else
# 使用 cargo 安装
if command -v cargo &> /dev/null; then
cargo install bat
else
echo "请先安装 Rust 和 Cargo"
exit 1
fi
fi
# 验证安装
if command -v bat &> /dev/null; then
echo "✅ bat 安装成功"
bat --version
else
echo "❌ bat 安装失败"
exit 1
fi
# 创建配置目录和文件
echo "配置 bat..."
mkdir -p ~/.config/bat
cat > ~/.config/bat/config << 'EOF'
# bat 配置文件
# 主题
--theme="TwoDark"
# 语法高亮
--style="numbers,changes,header"
# 网格线
--grid="2"
# 包装长行
--wrap="auto"
# 分页器
--pager="less -RF"
# 始终显示行号
--number
# 高亮修改行
--diff
EOF
# 下载更多主题
echo "下载额外主题..."
bat cache --build
# 创建别名
echo "创建别名..."
cat >> ~/.bashrc << 'EOF'
# bat 别名
alias cat='bat'
alias less='bat'
alias more='bat'
# 特殊用途别名
alias batp='bat --plain' # 无格式输出
alias batd='bat --diff' # 显示差异
alias baty='bat --language=yaml' # YAML 语法高亮
alias batj='bat --language=json' # JSON 语法高亮
EOF
echo "=== bat 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
2.2 高级使用示例
创建 bat 使用示例:bat_examples.sh
bash
#!/bin/bash
# bat 使用示例脚本
# 创建测试文件
create_test_files() {
echo "创建测试文件..."
# JSON 文件
cat > test.json << 'EOF'
{
"name": "示例项目",
"version": "1.0.0",
"dependencies": {
"react": "^17.0.0",
"typescript": "^4.0.0"
},
"scripts": {
"start": "node server.js",
"build": "webpack --mode production"
}
}
EOF
# YAML 文件
cat > test.yaml << 'EOF'
# 服务器配置
server:
port: 8080
host: localhost
# 数据库配置
database:
host: localhost
port: 5432
name: myapp
user: admin
# 功能开关
features:
logging: true
debug: false
cache: true
EOF
# Python 文件
cat > test.py << 'EOF'
#!/usr/bin/env python3
"""
示例 Python 脚本
"""
import json
import sys
from typing import List, Dict
class DataProcessor:
"""数据处理类"""
def __init__(self, config: Dict):
self.config = config
self.data = []
def load_data(self, filepath: str) -> List[Dict]:
"""加载数据"""
try:
with open(filepath, 'r') as f:
self.data = json.load(f)
return self.data
except Exception as e:
print(f"加载数据失败: {e}")
return []
def process_data(self) -> List[Dict]:
"""处理数据"""
return [item for item in self.data if item.get('active')]
def main():
"""主函数"""
processor = DataProcessor({"debug": True})
data = processor.load_data("data.json")
result = processor.process_data()
print(f"处理了 {len(result)} 条记录")
if __name__ == "__main__":
main()
EOF
# 配置文件
cat > test.conf << 'EOF'
# Nginx 配置示例
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
location /api {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
}
EOF
}
# 显示 bat 功能
demo_bat_features() {
echo "=== bat 功能演示 ==="
echo -e "\n1. 基础文件查看:"
echo "bat test.json"
bat test.json
echo -e "\n2. 显示行号:"
echo "bat -n test.py"
bat -n test.py
echo -e "\n3. 高亮特定语言:"
echo "bat -l yaml test.yaml"
bat -l yaml test.yaml
echo -e "\n4. 显示 Git 差异:"
echo "bat -d test.conf"
bat -d test.conf
echo -e "\n5. 无格式纯文本:"
echo "bat -p test.json"
bat -p test.json
echo -e "\n6. 主题预览:"
echo "bat --list-themes | head -10"
bat --list-themes | head -10
echo -e "\n7. 使用不同主题:"
echo "bat --theme=GitHub test.py"
bat --theme=GitHub test.py
}
# 清理测试文件
cleanup() {
rm -f test.json test.yaml test.py test.conf
echo "测试文件已清理"
}
# 主函数
main() {
create_test_files
demo_bat_features
cleanup
}
# 执行主函数
main
3. exa - 现代化的 ls
3.1 安装与配置
创建安装脚本:install_exa.sh
bash
#!/bin/bash
# exa 安装脚本
set -e
echo "=== 开始安装 exa ==="
# 检测系统并安装
if command -v apt-get &> /dev/null; then
# Ubuntu/Debian
wget https://github.com/ogham/exa/releases/download/v0.10.1/exa-linux-x86_64-v0.10.1.zip
unzip exa-linux-x86_64-v0.10.1.zip
sudo mv exa-linux-x86_64 /usr/local/bin/exa
rm exa-linux-x86_64-v0.10.1.zip
elif command -v yum &> /dev/null; then
# CentOS/RHEL
wget https://github.com/ogham/exa/releases/download/v0.10.1/exa-linux-x86_64-v0.10.1.zip
unzip exa-linux-x86_64-v0.10.1.zip
sudo mv exa-linux-x86_64 /usr/local/bin/exa
rm exa-linux-x86_64-v0.10.1.zip
elif command -v brew &> /dev/null; then
# macOS
brew install exa
else
# 使用 cargo 安装
if command -v cargo &> /dev/null; then
cargo install exa
else
echo "请先安装 Rust 和 Cargo"
exit 1
fi
fi
# 验证安装
if command -v exa &> /dev/null; then
echo "✅ exa 安装成功"
exa --version
else
echo "❌ exa 安装失败"
exit 1
fi
# 创建别名和函数
echo "配置 exa..."
cat >> ~/.bashrc << 'EOF'
# exa 配置
alias ls='exa'
alias ll='exa -l --git'
alias la='exa -la --git'
alias lt='exa --tree'
alias ltg='exa --tree --git'
# exa 彩色输出
export EXA_COLORS="di=34:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43"
# 函数:根据文件类型显示
l() {
if [ $# -eq 0 ]; then
exa -l --git
elif [ -d "$1" ]; then
exa -l --git "$1"
else
exa -l --git "$@"
fi
}
EOF
echo "=== exa 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
3.2 高级使用技巧
创建 exa 使用脚本:exa_advanced.sh
bash
#!/bin/bash
# exa 高级使用技巧
# 创建测试目录结构
create_test_structure() {
echo "创建测试目录结构..."
mkdir -p test_dir/{src,dist,docs,logs}
# 创建各种文件
touch test_dir/.env
touch test_dir/.gitignore
touch test_dir/README.md
touch test_dir/package.json
touch test_dir/src/main.py
touch test_dir/src/utils.js
touch test_dir/dist/app.exe
touch test_dir/docs/manual.pdf
touch test_dir/logs/app.log
# 设置不同权限
chmod +x test_dir/dist/app.exe
chmod 600 test_dir/.env
# 创建 Git 仓库测试 Git 状态
cd test_dir
git init > /dev/null 2>&1
git add . > /dev/null 2>&1
git config user.email "test@example.com" > /dev/null 2>&1
git config user.name "Test User" > /dev/null 2>&1
git commit -m "Initial commit" > /dev/null 2>&1
# 修改一些文件显示 Git 状态
echo "modified" > src/main.py
touch new_file.txt
cd ..
}
# 演示 exa 功能
demo_exa_features() {
cd test_dir
echo "=== exa 功能演示 ==="
echo -e "\n1. 基础列表:"
echo "exa"
exa
echo -e "\n2. 详细列表 (类 ls -l):"
echo "exa -l"
exa -l
echo -e "\n3. 显示 Git 状态:"
echo "exa -l --git"
exa -l --git
echo -e "\n4. 树状显示:"
echo "exa --tree"
exa --tree
echo -e "\n5. 树状显示带 Git 状态:"
echo "exa --tree --git"
exa --tree --git
echo -e "\n6. 显示文件大小:"
echo "exa -l --binary"
exa -l --binary
echo -e "\n7. 按时间排序:"
echo "exa -l --sort=modified"
exa -l --sort=modified
echo -e "\n8. 按大小排序:"
echo "exa -l --sort=size"
exa -l --sort=size
echo -e "\n9. 递归显示:"
echo "exa -R"
exa -R
echo -e "\n10. 显示所有文件 (包括隐藏文件):"
echo "exa -la"
exa -la
echo -e "\n11. 只显示目录:"
echo "exa -D"
exa -D
echo -e "\n12. 图标显示 (如果支持):"
echo "exa -l --icons"
exa -l --icons
cd ..
}
# 实用的 exa 函数
create_exa_functions() {
cat >> ~/.bashrc << 'EOF'
# exa 实用函数
# 查找大文件
find_large_files() {
exa -l --sort=size --reverse "$@" | head -10
}
# 查找最新文件
find_recent_files() {
exa -l --sort=modified --reverse "$@" | head -10
}
# 显示目录大小
dir_size() {
exa -l --binary --sort=size --reverse "$@" | grep '^d' | head -10
}
# Git 状态概览
git_status_overview() {
exa -la --git --group-directories-first
}
# 按类型显示
list_by_type() {
local file_type=$1
local path=${2:-.}
case $file_type in
"dir")
exa -D "$path"
;;
"file")
exa -l | grep -v '^d'
;;
"exec")
exa -l | grep '^-..x'
;;
"hidden")
exa -la | grep '^\.[^.]'
;;
*)
echo "用法: list_by_type {dir|file|exec|hidden} [path]"
;;
esac
}
EOF
}
# 清理
cleanup() {
rm -rf test_dir
echo "测试目录已清理"
}
main() {
create_test_structure
demo_exa_features
create_exa_functions
cleanup
echo -e "\n=== exa 配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令:"
echo " ll, la, lt, ltg, l"
echo " find_large_files, find_recent_files, dir_size, git_status_overview"
}
main
4. fd - 更简单快速的 find
4.1 安装与配置
创建安装脚本:install_fd.sh
bash
#!/bin/bash
# fd 安装脚本
set -e
echo "=== 开始安装 fd ==="
# 检测系统并安装
if command -v apt-get &> /dev/null; then
# Ubuntu/Debian
wget https://github.com/sharkdp/fd/releases/download/v8.3.0/fd_8.3.0_amd64.deb
sudo dpkg -i fd_8.3.0_amd64.deb
rm fd_8.3.0_amd64.deb
elif command -v yum &> /dev/null; then
# CentOS/RHEL
wget https://github.com/sharkdp/fd/releases/download/v8.3.0/fd-v8.3.0-x86_64-unknown-linux-gnu.tar.gz
tar -xzf fd-v8.3.0-x86_64-unknown-linux-gnu.tar.gz
sudo cp fd-v8.3.0-x86_64-unknown-linux-gnu/fd /usr/local/bin/
rm -rf fd-v8.3.0-x86_64-unknown-linux-gnu*
elif command -v brew &> /dev/null; then
# macOS
brew install fd
else
# 使用 cargo 安装
if command -v cargo &> /dev/null; then
cargo install fd-find
else
echo "请先安装 Rust 和 Cargo"
exit 1
fi
fi
# 验证安装
if command -v fd &> /dev/null; then
echo "✅ fd 安装成功"
fd --version
else
echo "❌ fd 安装失败"
exit 1
fi
# 创建别名和配置
echo "配置 fd..."
cat >> ~/.bashrc << 'EOF'
# fd 配置
alias find='fd'
# fd 实用函数
fdg() {
# 在 Git 仓库中搜索(忽略 .gitignore)
fd "$@" --hidden --no-ignore-vcs
}
fda() {
# 搜索所有文件(包括隐藏文件和忽略的文件)
fd "$@" --hidden --no-ignore
}
fde() {
# 按扩展名搜索
local ext=$1
shift
fd --extension "$ext" "$@"
}
fds() {
# 按大小搜索
local size=$1
shift
fd --size "$size" "$@"
}
fdu() {
# 搜索未跟踪的 Git 文件
git ls-files --others --exclude-standard | fd "$@"
}
EOF
echo "=== fd 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
4.2 高级使用示例
创建 fd 使用脚本:fd_examples.sh
bash
#!/bin/bash
# fd 使用示例和技巧
# 创建测试文件结构
create_test_files() {
echo "创建测试文件结构..."
mkdir -p fd_test/{src,dist,logs,docs,.hidden}
# 创建各种类型的文件
touch fd_test/.env
touch fd_test/.gitignore
touch fd_test/README.md
touch fd_test/package.json
touch fd_test/config.yaml
# 源代码文件
touch fd_test/src/main.py
touch fd_test/src/utils.js
touch fd_test/src/helper.ts
touch fd_test/src/style.css
touch fd_test/src/index.html
# 构建输出
touch fd_test/dist/app.js
touch fd_test/dist/app.css
touch fd_test/dist/app.exe
# 日志文件
touch fd_test/logs/app.log
touch fd_test/logs/error.log
touch fd_test/logs/debug.log
# 文档
touch fd_test/docs/manual.pdf
touch fd_test/docs/readme.txt
# 隐藏目录中的文件
touch fd_test/.hidden/secret.conf
touch fd_test/.hidden/backup.db
# 创建一些大文件
dd if=/dev/zero of=fd_test/large_file.dat bs=1M count=5 2>/dev/null
dd if=/dev/zero of=fd_test/src/big_library.so bs=1M count=3 2>/dev/null
echo "测试文件结构创建完成"
}
# 演示 fd 功能
demo_fd_features() {
cd fd_test
echo "=== fd 功能演示 ==="
echo -e "\n1. 基础搜索:"
echo "fd 'app'"
fd 'app'
echo -e "\n2. 忽略大小写:"
echo "fd -i 'readme'"
fd -i 'readme'
echo -e "\n3. 全字匹配:"
echo "fd -w 'app'"
fd -w 'app'
echo -e "\n4. 按扩展名搜索:"
echo "fd -e js"
fd -e js
echo -e "\n5. 按类型搜索:"
echo "fd -t f 'app' # 只搜索文件"
fd -t f 'app'
echo "fd -t d 'src' # 只搜索目录"
fd -t d 'src'
echo -e "\n6. 搜索隐藏文件:"
echo "fd -H 'secret'"
fd -H 'secret'
echo -e "\n7. 忽略 .gitignore:"
echo "fd -I 'large'"
fd -I 'large'
echo -e "\n8. 按大小搜索:"
echo "fd -S +1M # 大于 1MB"
fd -S +1M
echo "fd -S -100k # 小于 100KB"
fd -S -100k
echo -e "\n9. 按修改时间搜索:"
echo "fd --changed-within 1h"
fd --changed-within 1h
echo -e "\n10. 执行命令:"
echo "fd -e py -x echo 'Python file: {}'"
fd -e py -x echo 'Python file: {}'
echo -e "\n11. 使用正则表达式:"
echo "fd '^[a-z]+\\.log$' logs/"
fd '^[a-z]+\.log$' logs/
echo -e "\n12. 显示详细信息:"
echo "fd -l 'app'"
fd -l 'app'
echo -e "\n13. 计数结果:"
echo "fd -c 'app'"
fd -c 'app'
echo -e "\n14. 排除模式:"
echo "fd -E '*.log' app"
fd -E '*.log' app
cd ..
}
# 实用的 fd 工作流
create_fd_workflows() {
cat >> ~/.bashrc << 'EOF'
# fd 实用工作流
# 查找并删除临时文件
clean_tmp_files() {
fd -H '*.tmp' -X rm -v
fd -H '*.log' -S +100M -X rm -v
}
# 查找重复文件
find_duplicates() {
fd -t f -S +1k | xargs md5sum | sort | uniq -w32 -d
}
# 查找空文件/目录
find_empty() {
fd -t f -S 0
fd -t d -E '.*/\.git/.*' -x bash -c '[[ -z "$(ls -A {})" ]] && echo {}'
}
# 查找权限不安全的文件
find_unsafe_perms() {
fd -t f -x bash -c '[[ $(stat -c "%a" {}) =~ .*7$ ]] && echo {}'
}
# 批量重命名
batch_rename() {
local from_pattern=$1
local to_pattern=$2
fd -0 "$from_pattern" | xargs -0 rename "$from_pattern" "$to_pattern"
}
# 查找最近修改的文件
recent_files() {
local days=${1:-1}
fd --changed-within "${days}days" -l
}
# 在文件中搜索内容 (结合 grep)
fdgrep() {
local pattern=$1
local file_pattern=${2:-*}
fd "$file_pattern" -X grep -n "$pattern"
}
EOF
}
# 清理
cleanup() {
rm -rf fd_test
echo "测试文件已清理"
}
main() {
create_test_files
demo_fd_features
create_fd_workflows
cleanup
echo -e "\n=== fd 配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令:"
echo " fdg, fda, fde, fds, fdu"
echo " clean_tmp_files, find_duplicates, find_empty, batch_rename, recent_files, fdgrep"
}
main
5. ripgrep - 超快速代码搜索
5.1 安装与配置
创建安装脚本:install_ripgrep.sh
bash
#!/bin/bash
# ripgrep 安装脚本
set -e
echo "=== 开始安装 ripgrep ==="
# 检测系统并安装
if command -v apt-get &> /dev/null; then
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y ripgrep
elif command -v yum &> /dev/null; then
# CentOS/RHEL
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo=https://copr.fedorainproject.org/coprs/carlwgeorge/ripgrep/repo/epel-7/carlwgeorge-ripgrep-epel-7.repo
sudo yum install -y ripgrep
elif command -v brew &> /dev/null; then
# macOS
brew install ripgrep
else
# 下载预编译二进制文件
wget https://github.com/BurntSushi/ripgrep/releases/download/13.0.0/ripgrep-13.0.0-x86_64-unknown-linux-musl.tar.gz
tar -xzf ripgrep-13.0.0-x86_64-unknown-linux-musl.tar.gz
sudo cp ripgrep-13.0.0-x86_64-unknown-linux-musl/rg /usr/local/bin/
rm -rf ripgrep-13.0.0-x86_64-unknown-linux-musl*
fi
# 验证安装
if command -v rg &> /dev/null; then
echo "✅ ripgrep 安装成功"
rg --version
else
echo "❌ ripgrep 安装失败"
exit 1
fi
# 创建配置
echo "配置 ripgrep..."
mkdir -p ~/.config/ripgrep
cat > ~/.config/ripgrep/config << 'EOF'
# ripgrep 配置文件
# 默认启用彩色输出
--color=auto
# 显示行号
--line-number
# 搜索时忽略 .gitignore 文件
--hidden
# 搜索时遵循 .gitignore
--glob='!.git/*'
# 智能大小写(如果模式全小写则忽略大小写)
--smart-case
# 最大列数(防止在宽文件中输出过长)
--max-columns=150
# 预览上下文
--context=3
--before-context=2
--after-context=2
# 颜色配置
--colors='line:fg:green'
--colors='path:fg:blue'
--colors='match:fg:red'
--colors='match:style:nobold'
EOF
# 创建别名和函数
cat >> ~/.bashrc << 'EOF'
# ripgrep 配置
alias grep='rg'
alias gi='rg -i' # 忽略大小写
# ripgrep 实用函数
rgg() {
# 在 Git 跟踪的文件中搜索
rg "$@" --type-not git
}
rgh() {
# 搜索隐藏文件
rg "$@" --hidden -g '!*.git*'
}
rgt() {
# 按文件类型搜索
local file_type=$1
shift
rg "$@" --type "$file_type"
}
rgu() {
# 搜索未跟踪的 Git 文件
git ls-files --others --exclude-standard | xargs rg "$@" || true
}
rgf() {
# 只显示文件名
rg "$@" --files-with-matches
}
rgc() {
# 统计匹配数量
rg "$@" --count
}
# 复杂的代码搜索
code_search() {
local pattern=$1
local path=${2:-.}
rg \
--smart-case \
--type-add 'config:*.{json,yaml,yml,toml,ini,conf}' \
--type-add 'script:*.{sh,bash,zsh,py,js,ts,php,rb}' \
--type-add 'doc:*.{md,mdx,txt,rst}' \
"$pattern" "$path"
}
EOF
echo "=== ripgrep 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
5.2 高级使用技巧
创建 ripgrep 示例脚本:ripgrep_examples.sh
bash
#!/bin/bash
# ripgrep 高级使用示例
# 创建测试代码库
create_test_repo() {
echo "创建测试代码库..."
mkdir -p rg_test/{src,config,docs,scripts,tests}
# 创建各种代码文件
cat > rg_test/src/main.py << 'EOF'
#!/usr/bin/env python3
"""
主程序入口
"""
import sys
import json
from utils import logger, config_loader
CONFIG_FILE = "config/app.json"
def load_config():
"""加载配置文件"""
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except FileNotFoundError:
logger.error(f"配置文件不存在: {CONFIG_FILE}")
return {}
def main():
"""主函数"""
config = load_config()
# 数据库配置
db_host = config.get('database', {}).get('host', 'localhost')
db_port = config.get('database', {}).get('port', 5432)
logger.info(f"数据库连接: {db_host}:{db_port}")
# 启动应用
app_name = config.get('app_name', 'MyApp')
logger.info(f"启动应用: {app_name}")
return 0
if __name__ == "__main__":
sys.exit(main())
EOF
cat > rg_test/src/utils.py << 'EOF'
"""
工具函数模块
"""
import logging
import os
from typing import Dict, Any
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def config_loader(config_path: str) -> Dict[str, Any]:
"""配置加载器"""
import json
try:
with open(config_path, 'r') as f:
return json.load(f)
except Exception as e:
logger.error(f"加载配置失败: {e}")
return {}
def validate_config(config: Dict[str, Any]) -> bool:
"""验证配置"""
required_keys = ['app_name', 'database']
return all(key in config for key in required_keys)
# 常量定义
DEFAULT_TIMEOUT = 30
MAX_RETRIES = 3
EOF
cat > rg_test/config/app.json << 'EOF'
{
"app_name": "MyApplication",
"version": "1.0.0",
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp",
"user": "admin"
},
"logging": {
"level": "INFO",
"file": "/var/log/myapp.log"
},
"features": {
"debug": true,
"cache": true
}
}
EOF
cat > rg_test/scripts/deploy.sh << 'EOF'
#!/bin/bash
# 部署脚本
set -e
CONFIG_FILE="config/app.json"
BACKUP_DIR="backups"
LOG_FILE="deploy.log"
# 日志函数
log() {
echo "$(date): $1" >> "$LOG_FILE"
echo "$1"
}
# 加载配置
if [ ! -f "$CONFIG_FILE" ]; then
log "错误: 配置文件不存在: $CONFIG_FILE"
exit 1
fi
# 解析配置
APP_NAME=$(jq -r '.app_name' "$CONFIG_FILE")
DB_HOST=$(jq -r '.database.host' "$CONFIG_FILE")
log "开始部署应用: $APP_NAME"
log "数据库主机: $DB_HOST"
# 部署逻辑
log "部署完成"
EOF
cat > rg_test/docs/README.md << 'EOF'
# MyApplication
这是一个示例应用程序。
## 功能特性
- 配置驱动
- 日志记录
- 数据库支持
## 配置
编辑 `config/app.json` 文件:
```json
{
"app_name": "MyApplication",
"database": {
"host": "localhost"
}
}
部署
运行部署脚本:
bash
./scripts/deploy.sh
EOF
bash
# 创建一些隐藏文件和备份文件
touch rg_test/.env
touch rg_test/src/__pycache__/temp.pyc
touch rg_test/backup_2023.sql
echo "测试代码库创建完成"
}
演示 ripgrep 功能
demo_ripgrep_features() { cd rg_test
bash
echo "=== ripgrep 功能演示 ==="
echo -e "\n1. 基础搜索:"
echo "rg 'config'"
rg 'config'
echo -e "\n2. 忽略大小写:"
echo "rg -i 'database'"
rg -i 'database'
echo -e "\n3. 单词匹配:"
echo "rg -w 'log'"
rg -w 'log'
echo -e "\n4. 显示上下文:"
echo "rg -C 2 'app_name'"
rg -C 2 'app_name'
echo -e "\n5. 只显示文件名:"
echo "rg -l 'localhost'"
rg -l 'localhost'
echo -e "\n6. 统计匹配数:"
echo "rg -c 'config'"
rg -c 'config'
echo -e "\n7. 按文件类型搜索:"
echo "rg -t py 'import'"
rg -t py 'import'
echo "rg -t sh 'set'"
rg -t sh 'set'
echo -e "\n8. 排除文件类型:"
echo "rg -T json 'localhost'"
rg -T json 'localhost'
echo -e "\n9. 搜索隐藏文件:"
echo "rg --hidden 'env'"
rg --hidden 'env'
echo -e "\n10. 使用正则表达式:"
echo "rg 'log(ger)?\\.'"
rg 'log(ger)?\.'
echo -e "\n11. 替换文本:"
echo "rg 'localhost' -r '127.0.0.1'"
rg 'localhost' -r '127.0.0.1'
echo -e "\n12. 多模式搜索:"
echo "rg -e 'config' -e 'database'"
rg -e 'config' -e 'database'
echo -e "\n13. 搜索特定目录:"
echo "rg 'function' src/"
rg 'function' src/
echo -e "\n14. 忽略大小写和显示行号:"
echo "rg -in 'error'"
rg -in 'error'
cd ..
}
实用的代码搜索工作流
create_ripgrep_workflows() { cat >> ~/.bashrc << 'EOF'
ripgrep 代码搜索工作流
查找 TODO 注释
find_todos() { rg -i "TODO|FIXME|XXX|HACK" "$@" }
查找函数定义
find_functions() { rg -n "^(def|function|class|fn)\s+\w+" "$@" }
查找配置项
find_configs() { rg -i "config|setting|option" "$@" }
查找错误处理
find_errors() { rg -i "error|exception|catch|throw" "$@" }
查找日志语句
find_logs() { rg -i "log(ger)?\.(info|debug|warn|error)" "$@" }
查找硬编码的字符串
find_hardcoded() { rg '".*@"' " <math xmlns="http://www.w3.org/1998/Math/MathML"> @ " ∣ ∣ t r u e r g " ′ . ∗ @ ′ " " @" || true rg "'.*@'" " </math>@"∣∣truerg"′.∗@′""@" || true }
查找数据库相关代码
find_database() { rg -i "select|insert|update|delete|from|where" "$@" }
复杂的代码分析
code_analysis() { local path=${1:-.}
bash
echo "=== 代码分析报告 ==="
echo
echo "TODO 注释:"
find_todos "$path" | head -10
echo
echo "函数定义:"
find_functions "$path" | head -10
echo
echo "错误处理:"
find_errors "$path" | head -10
} EOF }
性能测试
performance_test() { echo -e "\n=== 性能测试 ==="
bash
# 创建大文件进行测试
for i in {1..1000}; do
echo "这是测试行 $i" >> rg_test/large_file.txt
echo "config_value = $i" >> rg_test/large_file.txt
echo "function test_$i() {}" >> rg_test/large_file.txt
done
echo "使用 ripgrep 搜索:"
time rg "config_value" rg_test/large_file.txt > /dev/null
echo -e "\n使用 grep 搜索:"
time grep "config_value" rg_test/large_file.txt > /dev/null
rm rg_test/large_file.txt
}
清理
cleanup() { rm -rf rg_test echo "测试文件已清理" }
main() { create_test_repo demo_ripgrep_features performance_test create_ripgrep_workflows cleanup
bash
echo -e "\n=== ripgrep 配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令:"
echo " rgg, rgh, rgt, rgu, rgf, rgc"
echo " find_todos, find_functions, find_configs, find_errors, find_logs, code_analysis"
}
main
bash
## 6. tldr - 简化的 man 页面
### 6.1 安装与配置
```bash
#!/bin/bash
# tldr 安装脚本
set -e
echo "=== 开始安装 tldr ==="
# 检测系统并安装
if command -v npm &> /dev/null; then
# 使用 npm 安装
sudo npm install -g tldr
elif command -v pip &> /dev/null; then
# 使用 pip 安装
pip install tldr
elif command -v apt-get &> /dev/null; then
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y tldr
elif command -v brew &> /dev/null; then
# macOS
brew install tldr
else
# 下载二进制文件
wget https://github.com/tldr-pages/tldr-cpp-client/releases/download/1.5.0/tldr-linux-x86_64.zip
unzip tldr-linux-x86_64.zip
sudo mv tldr /usr/local/bin/
rm tldr-linux-x86_64.zip
fi
# 验证安装
if command -v tldr &> /dev/null; then
echo "✅ tldr 安装成功"
tldr --version
else
echo "❌ tldr 安装失败"
exit 1
fi
# 更新缓存
echo "更新 tldr 缓存..."
tldr --update
# 创建别名和函数
cat >> ~/.bashrc << 'EOF'
# tldr 配置
alias help='tldr'
alias man='tldr'
# tldr 实用函数
tldr_search() {
tldr --search "$@"
}
tldr_list() {
tldr --list | fzf --preview "tldr {}" --preview-window=right:70%
}
tldr_update() {
tldr --update
}
# 常用命令速查
cheat() {
local cmd=$1
case $cmd in
"tar")
echo "压缩: tar -czf archive.tar.gz dir/"
echo "解压: tar -xzf archive.tar.gz"
echo "查看: tar -tzf archive.tar.gz"
;;
"find")
echo "按名: find . -name '*.txt'"
echo "按类型: find . -type f"
echo "按时间: find . -mtime -7"
;;
"grep")
echo "递归: grep -r 'pattern' ."
echo "忽略大小写: grep -i 'pattern' file"
echo "显示行号: grep -n 'pattern' file"
;;
"ssh")
echo "连接: ssh user@host"
echo "端口: ssh -p 2222 user@host"
echo "密钥: ssh -i key.pem user@host"
;;
*)
tldr "$cmd"
;;
esac
}
EOF
echo "=== tldr 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
7. htop - 增强型系统监控
7.1 安装与高级配置
bash
#!/bin/bash
# htop 安装和配置脚本
set -e
echo "=== 开始安装 htop ==="
# 安装 htop
if command -v apt-get &> /dev/null; then
sudo apt-get update
sudo apt-get install -y htop
elif command -v yum &> /dev/null; then
sudo yum install -y htop
elif command -v brew &> /dev/null; then
brew install htop
else
# 从源码编译
wget https://github.com/htop-dev/htop/archive/refs/tags/3.2.1.tar.gz
tar -xzf 3.2.1.tar.gz
cd htop-3.2.1
./autogen.sh
./configure
make
sudo make install
cd ..
rm -rf htop-3.2.1 3.2.1.tar.gz
fi
# 验证安装
if command -v htop &> /dev/null; then
echo "✅ htop 安装成功"
htop --version
else
echo "❌ htop 安装失败"
exit 1
fi
# 创建配置文件
echo "配置 htop..."
mkdir -p ~/.config/htop
cat > ~/.config/htop/htoprc << 'EOF'
# htop 配置文件
# 显示选项
fields=0 48 17 18 38 39 40 2 46 47 49 1
sort_key=46
sort_direction=1
hide_threads=0
hide_kernel_threads=1
hide_userland_threads=0
shadow_other_users=0
show_thread_names=0
show_program_path=1
highlight_base_name=0
highlight_megabytes=1
highlight_threads=1
tree_view=0
header_margin=1
detailed_cpu_time=0
cpu_count_from_zero=0
update_process_names=0
account_guest_in_cpu_meter=0
color_scheme=0
delay=15
left_meters=AllCPUs Memory Swap
left_meter_modes=1 1 1
right_meters=Tasks LoadAverage Uptime
right_meter_modes=2 2 2
# 颜色配置
# 0: 黑底白字
# 1: 终端默认
# 2: 亮色背景
# 3: 黑底灰字
# 4: 黑底绿字
# 5: 黑底红字
# 6: 白底黑字
EOF
# 创建监控脚本
cat > ~/bin/system_monitor.sh << 'EOF'
#!/bin/bash
# 系统监控脚本
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# 监控函数
monitor_cpu() {
echo -e "${BLUE}=== CPU 使用率 ===${NC}"
mpstat 1 1 | grep -A5 "Average"
}
monitor_memory() {
echo -e "${GREEN}=== 内存使用 ===${NC}"
free -h
}
monitor_disk() {
echo -e "${YELLOW}=== 磁盘使用 ===${NC}"
df -h | grep -E "(Filesystem|/dev/sd)"
}
monitor_network() {
echo -e "${BLUE}=== 网络连接 ===${NC}"
netstat -an | grep -c ESTABLISHED | awk '{print "ESTABLISHED 连接数:", $1}'
}
monitor_processes() {
echo -e "${GREEN}=== 进程监控 ===${NC}"
ps aux --sort=-%cpu | head -10
}
# 持续监控模式
continuous_monitor() {
watch -n 2 '
echo "====== 系统监控 ======"
echo "时间: $(date)"
echo
echo "CPU 负载: $(uptime | awk -F"load average:" "{print \$2}")"
echo "内存使用: $(free -h | grep Mem | awk "{print \$3\"/\"\$2}")"
echo "磁盘使用: $(df -h / | tail -1 | awk "{print \$5}")"
echo
echo "Top 进程:"
ps aux --sort=-%cpu | head -5
'
}
# 告警检查
check_alerts() {
# CPU 告警
local cpu_load=$(uptime | awk -F'load average:' '{print $2}' | awk -F, '{print $1}' | tr -d ' ')
if (( $(echo "$cpu_load > 5.0" | bc -l) )); then
echo -e "${RED}警告: CPU 负载过高: $cpu_load${NC}"
fi
# 内存告警
local mem_free=$(free -m | awk 'NR==2{print $4}')
if [ $mem_free -lt 100 ]; then
echo -e "${RED}警告: 可用内存不足: ${mem_free}MB${NC}"
fi
# 磁盘告警
local disk_usage=$(df / | awk 'NR==2{print $5}' | sed 's/%//')
if [ $disk_usage -gt 90 ]; then
echo -e "${RED}警告: 根分区使用率过高: ${disk_usage}%${NC}"
fi
}
case "$1" in
"cpu")
monitor_cpu
;;
"memory")
monitor_memory
;;
"disk")
monitor_disk
;;
"network")
monitor_network
;;
"process")
monitor_processes
;;
"watch")
continuous_monitor
;;
"alert")
check_alerts
;;
"all"|"")
monitor_cpu
echo
monitor_memory
echo
monitor_disk
echo
monitor_network
echo
monitor_processes
echo
check_alerts
;;
*)
echo "用法: $0 {cpu|memory|disk|network|process|watch|alert|all}"
;;
esac
EOF
chmod +x ~/bin/system_monitor.sh
# 创建别名
cat >> ~/.bashrc << 'EOF'
# htop 别名和函数
alias top='htop'
alias monitor='~/bin/system_monitor.sh'
# 快速监控命令
cpu_mon() {
watch -n 1 'echo "CPU 使用率:" && mpstat 1 1 | grep "Average"'
}
mem_mon() {
watch -n 1 'echo "内存使用:" && free -h'
}
io_mon() {
watch -n 1 'echo "IO 统计:" && iostat -x 1 1'
}
# 进程查找和监控
find_process() {
local pattern=$1
htop -p $(pgrep -f "$pattern" | tr '\n' ',' | sed 's/,$//')
}
# 系统健康检查
health_check() {
echo "=== 系统健康检查 ==="
~/bin/system_monitor.sh alert
echo
echo "最近重启:"
last reboot | head -5
echo
echo "系统日志错误:"
journalctl -p 3 -xb --no-pager | head -10
}
EOF
echo "=== htop 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令: monitor, cpu_mon, mem_mon, io_mon, find_process, health_check"
8. zoxide - 智能目录跳转
8.1 安装与配置
bash
#!/bin/bash
# zoxide 安装脚本
set -e
echo "=== 开始安装 zoxide ==="
# 检测系统并安装
if command -v curl &> /dev/null; then
# 使用官方安装脚本
curl -sSf https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | sh
elif command -v apt-get &> /dev/null; then
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y zoxide
elif command -v brew &> /dev/null; then
# macOS
brew install zoxide
else
# 下载预编译二进制
wget https://github.com/ajeetdsouza/zoxide/releases/download/v0.8.3/zoxide-0.8.3-x86_64-unknown-linux-musl.tar.gz
tar -xzf zoxide-0.8.3-x86_64-unknown-linux-musl.tar.gz
sudo cp zoxide /usr/local/bin/
rm zoxide zoxide-0.8.3-x86_64-unknown-linux-musl.tar.gz
fi
# 验证安装
if command -v zoxide &> /dev/null; then
echo "✅ zoxide 安装成功"
zoxide --version
else
echo "❌ zoxide 安装失败"
exit 1
fi
# 初始化 zoxide
echo "初始化 zoxide..."
eval "$(zoxide init bash)"
# 创建配置
cat >> ~/.bashrc << 'EOF'
# zoxide 配置
export _ZO_DATA_DIR="$HOME/.local/share/zoxide"
export _ZO_MAXAGE=1000
# zoxide 别名
alias z='__zoxide_z'
alias zi='__zoxide_zi'
alias cd='z'
# zoxide 实用函数
zq() {
# 快速跳转到常用目录
case $1 in
"code")
z ~/code
;;
"doc")
z ~/Documents
;;
"down")
z ~/Downloads
;;
"conf")
z ~/.config
;;
"log")
z /var/log
;;
"temp")
z /tmp
;;
*)
z "$1"
;;
esac
}
# 目录书签功能
export CODE_DIR="$HOME/code"
export WORK_DIR="$HOME/work"
export CONFIG_DIR="$HOME/.config"
# 跳转到包含特定文件的目录
zf() {
local file_pattern=$1
local dir
dir=$(find . -name "$file_pattern" -type f | head -1 | xargs dirname)
if [ -n "$dir" ]; then
z "$dir"
else
echo "未找到包含 $file_pattern 的目录"
fi
}
# 最近访问的目录
zr() {
zoxide query -l | fzf --height 40% | xargs z
}
# 添加当前目录到 zoxide 数据库
za() {
zoxide add "$(pwd)"
echo "已添加: $(pwd)"
}
# zoxide 统计
zstats() {
echo "=== zoxide 目录统计 ==="
zoxide query -l | head -10
echo
echo "最常访问的目录:"
zoxide query -s | head -5
}
EOF
# 创建测试目录并添加一些路径
echo "创建测试目录并初始化数据库..."
mkdir -p ~/test_dirs/{project1,project2,work,personal}
for dir in ~/test_dirs/*; do
cd "$dir" && zoxide add "$dir"
done
cd ~
echo "=== zoxide 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令: z, zi, zq, zf, zr, za, zstats"
9. dust - 磁盘使用分析
9.1 安装与使用
bash
#!/bin/bash
# dust 安装脚本
set -e
echo "=== 开始安装 dust ==="
# 检测系统并安装
if command -v cargo &> /dev/null; then
cargo install du-dust
elif command -v brew &> /dev/null; then
brew install dust
else
# 下载预编译二进制
wget https://github.com/bootandy/dust/releases/download/v0.8.3/dust-v0.8.3-x86_64-unknown-linux-musl.tar.gz
tar -xzf dust-v0.8.3-x86_64-unknown-linux-musl.tar.gz
sudo cp dust /usr/local/bin/
rm dust dust-v0.8.3-x86_64-unknown-linux-musl.tar.gz
fi
# 验证安装
if command -v dust &> /dev/null; then
echo "✅ dust 安装成功"
dust --version
else
echo "❌ dust 安装失败"
exit 1
fi
# 创建别名和函数
cat >> ~/.bashrc << 'EOF'
# dust 配置
alias du='dust'
alias dus='dust -r'
# dust 实用函数
disk_usage() {
local path=${1:-.}
dust "$path"
}
large_files() {
# 查找大文件
local path=${1:-.}
find "$path" -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -hr
}
large_dirs() {
# 查找大目录
local path=${1:-.}
dust -r "$path" | head -20
}
clean_disk() {
# 磁盘清理建议
echo "=== 磁盘清理建议 ==="
# 查找日志文件
echo -e "\n大日志文件:"
find /var/log -type f -size +100M 2>/dev/null | head -5
# 查找缓存文件
echo -e "\n缓存目录大小:"
dust ~/.cache 2>/dev/null | head -3
# 查找临时文件
echo -e "\n临时文件:"
find /tmp -type f -atime +7 -size +10M 2>/dev/null | head -5
}
# 按类型分析磁盘使用
analyze_by_type() {
local path=${1:-.}
echo "=== 按文件类型分析 ==="
find "$path" -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn | head -10
}
# 监控磁盘增长
disk_growth() {
local path=${1:-.}
local interval=${2:-60}
while true; do
clear
echo "=== 磁盘使用监控 ($(date)) ==="
dust -r "$path" | head -15
sleep "$interval"
done
}
EOF
# 创建磁盘分析报告脚本
cat > ~/bin/disk_report.sh << 'EOF'
#!/bin/bash
# 磁盘分析报告脚本
echo "====== 磁盘使用分析报告 ======"
echo "生成时间: $(date)"
echo
# 总体磁盘使用
echo "1. 总体磁盘使用:"
df -h | grep -E "(Filesystem|/dev/sd)"
echo
# 主目录使用情况
echo "2. 主目录分析:"
dust ~ -d 1 | head -10
echo
# 大文件分析
echo "3. 大文件分析 (前10个):"
find ~ -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -hr | head -10
echo
# 按类型分析
echo "4. 按文件类型分析:"
find ~ -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn | head -10
echo
# 清理建议
echo "5. 清理建议:"
echo "• 检查 ~/.cache 目录"
echo "• 清理下载目录"
echo "• 删除旧的日志文件"
echo "• 考虑压缩大文件"
EOF
chmod +x ~/bin/disk_report.sh
echo "=== dust 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令: disk_usage, large_files, large_dirs, clean_disk, analyze_by_type, disk_growth"
echo "生成报告: ~/bin/disk_report.sh"
10. lazygit - 终端 Git UI
10.1 安装与配置
bash
#!/bin/bash
# lazygit 安装脚本
set -e
echo "=== 开始安装 lazygit ==="
# 检测系统并安装
if command -v go &> /dev/null; then
# 使用 go 安装
go install github.com/jesseduffield/lazygit@latest
elif command -v brew &> /dev/null; then
# macOS
brew install lazygit
else
# 下载预编译二进制
LAZYGIT_VERSION=$(curl -s "https://api.github.com/repos/jesseduffield/lazygit/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
curl -Lo lazygit.tar.gz "https://github.com/jesseduffield/lazygit/releases/latest/download/lazygit_${LAZYGIT_VERSION:1}_Linux_x86_64.tar.gz"
tar xf lazygit.tar.gz lazygit
sudo install lazygit /usr/local/bin
rm lazygit lazygit.tar.gz
fi
# 验证安装
if command -v lazygit &> /dev/null; then
echo "✅ lazygit 安装成功"
lazygit --version
else
echo "❌ lazygit 安装失败"
exit 1
fi
# 创建配置目录
echo "配置 lazygit..."
mkdir -p ~/.config/lazygit
# 创建配置文件
cat > ~/.config/lazygit/config.yml << 'EOF'
gui:
theme:
lightTheme: false
activeBorderColor:
- "#a6e3a1"
inactiveBorderColor:
- "#45475a"
optionsTextColor:
- "#89b4fa"
selectedLineBgColor:
- "#313244"
selectedRangeBgColor:
- "#313244"
commitLength:
show: true
mouseEvents: true
skipUnstageLineWarning: false
skipStashWarning: true
showFileTree: true
showListFooter: true
showRandomTip: false
showCommandLog: true
commandLogSize: 8
git:
paging:
colorArg: always
useConfig: false
merging:
manualCommit: false
args: ""
skipHookPrefix: WIP
autoFetch: true
branchLogCmd: "git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --"
os:
edit: ${EDITOR:-vim}
open: xdg-open
update:
method: prompt
reporting: "undetermined"
confirmOnQuit: false
keybinding:
universal:
quit: "q"
quit-alt1: "<c-c>"
return: "<esc>"
quitWithoutChangingDirectory: "Q"
togglePanel: "<tab>"
prevItem: "k"
nextItem: "j"
prevItem-alt: "<up>"
nextItem-alt: "<down>"
prevPage: "<"
nextPage: ">"
gotoTop: "g"
gotoBottom: "G"
prevBlock: "<left>"
nextBlock: "<right>"
nextBlock-alt: "l"
prevBlock-alt: "h"
nextMatch: "n"
prevMatch: "N"
startSearch: "/"
optionMenu: "x"
optionMenu-alt1: "?"
select: "<space>"
goInto: "<enter>"
confirm: "<enter>"
confirm-alt1: "y"
remove: "d"
new: "n"
edit: "e"
openFile: "o"
scrollUpMain: "<c-u>"
scrollDownMain: "<c-d>"
scrollUpMain-alt1: "K"
scrollDownMain-alt1: "J"
scrollUpMain-alt2: "<c-b>"
scrollDownMain-alt2: "<c-f>"
executeCustomCommand: ":"
createRebaseOptionsMenu: "m"
pushFiles: "P"
pullFiles: "p"
refresh: "R"
createPatchOptionsMenu: "<c-p>"
nextTab: "]"
prevTab: "["
nextScreenMode: "+"
prevScreenMode: "_"
undo: "z"
redo: "<c-z>"
filteringMenu: "<c-s>"
diffingMenu: "W"
diffingMenu-alt: "<c-e>"
copyToClipboard: "<c-o>"
openRecentRepos: "<c-r>"
submitEditorText: "<enter>"
appendNewline: "<a-enter>"
status:
checkForUpdate: "u"
recentRepos: "<enter>"
files:
commitChanges: "c"
commitChangesWithoutHook: "C"
amendLastCommit: "A"
commitChangesWithEditor: "<c-c>"
ignoreFile: "i"
refreshFiles: "r"
stagingToggle: "s"
stageAll: "a"
unstageAll: "A"
viewResetOptions: "D"
fetch: "f"
toggleStagedAll: "<c-a>"
branches:
createPullRequest: "o"
viewPullRequestOptions: "O"
checkoutBranchByName: "c"
forceCheckoutBranch: "F"
rebaseBranch: "r"
renameBranch: "R"
mergeIntoCurrentBranch: "M"
viewGitFlowOptions: "i"
fastForward: "f"
pushTag: "P"
setUpstream: "u"
fetchRemote: "f"
commits:
squashDown: "s"
renameCommit: "r"
renameCommitWithEditor: "R"
viewResetOptions: "g"
markCommitAsFixup: "f"
createFixupCommit: "F"
squashAboveCommits: "S"
moveDownCommit: "<c-j>"
moveUpCommit: "<c-k>"
amendToCommit: "A"
pickCommit: "p"
revertCommit: "t"
cherryPickCopy: "c"
cherryPickCopyRange: "C"
pasteCommits: "v"
tagCommit: "T"
checkoutCommit: "<space>"
resetCherryPick: "<c-R>"
copyCommitAttribute: "y"
openLogMenu: "<c-l>"
stash:
popStash: "g"
commitFiles:
checkoutCommitFile: "c"
main:
toggleDragSelect: "v"
toggleDragSelect-alt: "V"
toggleSelectHunk: "a"
pickBothHunks: "b"
submodules:
init: "i"
update: "u"
bulkMenu: "b"
EOF
# 创建别名和实用函数
cat >> ~/.bashrc << 'EOF'
# lazygit 配置
alias lg='lazygit'
alias gitui='lazygit'
# lazygit 实用函数
git_status() {
lazygit status
}
git_log() {
lazygit log
}
git_commit() {
lazygit commit
}
git_branch() {
lazygit branch
}
# 快速提交
quick_commit() {
local message=$1
if [ -z "$message" ]; then
message="Update $(date '+%Y-%m-%d %H:%M:%S')"
fi
git add .
git commit -m "$message"
lazygit
}
# Git 工作流
git_workflow() {
case $1 in
"feature")
echo "开始新功能开发..."
lazygit
;;
"bugfix")
echo "开始 bug 修复..."
lazygit
;;
"release")
echo "准备发布..."
lazygit
;;
*)
lazygit
;;
esac
}
# 多仓库管理
git_multi() {
local repo_dirs=(
"$HOME/code"
"$HOME/work"
"$HOME/projects"
)
local selected_dir
selected_dir=$(find "${repo_dirs[@]}" -name ".git" -type d 2>/dev/null |
sed 's/\/.git//' |
fzf --height 40% --prompt="选择 Git 仓库: ")
if [ -n "$selected_dir" ]; then
cd "$selected_dir"
lazygit
fi
}
# Git 统计
git_stats() {
echo "=== Git 仓库统计 ==="
echo
echo "提交次数: $(git rev-list --count HEAD 2>/dev/null || echo "N/A")"
echo
echo "最近提交:"
git log --oneline -5 2>/dev/null || echo "无 Git 仓库"
echo
echo "分支情况:"
git branch -a 2>/dev/null | head -10 || echo "无 Git 仓库"
}
EOF
# 创建测试 Git 仓库用于演示
echo "创建测试 Git 仓库..."
mkdir -p ~/test_lazygit_repo
cd ~/test_lazygit_repo
git init
echo "# 测试项目" > README.md
git add .
git config user.email "test@example.com"
git config user.name "Test User"
git commit -m "Initial commit" > /dev/null 2>&1
cd ~
echo "=== lazygit 安装配置完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用命令: lg, gitui, git_status, git_log, quick_commit, git_workflow, git_multi, git_stats"
echo "测试仓库: ~/test_lazygit_repo"
工具整合与工作流
创建综合配置脚本
bash
#!/bin/bash
# 命令行工具整合脚本
echo "=== 安装所有命令行神器 ==="
# 定义工具列表
tools=(
"fzf"
"bat"
"exa"
"fd"
"ripgrep"
"tldr"
"htop"
"zoxide"
"dust"
"lazygit"
)
# 安装所有工具
for tool in "${tools[@]}"; do
echo "安装 $tool..."
if [ -f "install_${tool}.sh" ]; then
bash "install_${tool}.sh"
else
echo "找不到安装脚本: install_${tool}.sh"
fi
echo
done
# 创建综合配置文件
cat > ~/.bash_aliases << 'EOF'
# 命令行工具综合配置
# 工具检查
has_command() {
command -v "$1" > /dev/null 2>&1
}
# 如果工具存在则设置别名
if has_command fzf; then
source ~/.config/fzf/fzf.sh
source ~/fzf_helpers.sh
fi
if has_command bat; then
alias cat='bat'
alias less='bat'
fi
if has_command exa; then
alias ls='exa'
alias ll='exa -l --git'
alias la='exa -la --git'
alias lt='exa --tree'
fi
if has_command fd; then
alias find='fd'
fi
if has_command rg; then
alias grep='rg'
fi
if has_command tldr; then
alias help='tldr'
fi
if has_command htop; then
alias top='htop'
fi
if has_command zoxide; then
eval "$(zoxide init bash)"
alias cd='z'
fi
if has_command dust; then
alias du='dust'
fi
if has_command lazygit; then
alias lg='lazygit'
fi
# 综合工作流函数
dev_workflow() {
# 开发工作流
local project_dir=${1:-.}
echo "=== 开发工作流 ==="
cd "$project_dir"
# 显示项目状态
echo "项目状态:"
if [ -d .git ]; then
git status
else
echo "非 Git 项目"
fi
echo
echo "文件结构:"
exa --tree --git | head -20
echo
echo "最近修改:"
find . -type f -mtime -7 | head -10
}
sys_check() {
# 系统检查工作流
echo "=== 系统检查 ==="
echo "1. 系统资源:"
htop --sort-key=PERCENT_CPU | head -10
echo
echo "2. 磁盘使用:"
dust -r / | head -10
echo
echo "3. 大文件:"
find ~ -type f -size +100M -exec ls -lh {} \; 2>/dev/null | head -5
echo
echo "4. 网络连接:"
netstat -an | grep -c ESTABLISHED | awk '{print "活跃连接:", $1}'
}
code_search_workflow() {
# 代码搜索工作流
local pattern=$1
local path=${2:-.}
echo "=== 代码搜索: $pattern ==="
echo "1. 文件搜索:"
fd "$pattern" "$path" | head -10
echo
echo "2. 内容搜索:"
rg "$pattern" "$path" | head -10
echo
echo "3. Git 历史:"
git log --oneline --grep="$pattern" 2>/dev/null | head -5 || echo "无 Git 历史"
}
file_management() {
# 文件管理工作流
local path=${1:-.}
echo "=== 文件管理: $path ==="
echo "1. 目录结构:"
exa --tree "$path" | head -20
echo
echo "2. 文件统计:"
find "$path" -type f | wc -l | awk '{print "文件数量:", $1}'
du -sh "$path" | awk '{print "总大小:", $1}'
echo
echo "3. 最近修改:"
exa -l --sort=modified "$path" | head -10
}
# 快速导航
quick_nav() {
case $1 in
"code") z ~/code ;;
"work") z ~/work ;;
"tmp") z /tmp ;;
"log") z /var/log ;;
"conf") z ~/.config ;;
"download") z ~/Downloads ;;
"doc") z ~/Documents ;;
*) z "$1" ;;
esac
}
# 工具状态检查
tool_status() {
echo "=== 命令行工具状态 ==="
local tools=("fzf" "bat" "exa" "fd" "rg" "tldr" "htop" "zoxide" "dust" "lazygit")
for tool in "${tools[@]}"; do
if has_command "$tool"; then
echo "✅ $tool: $(command -v "$tool")"
else
echo "❌ $tool: 未安装"
fi
done
}
EOF
# 添加到 bashrc
echo "source ~/.bash_aliases" >> ~/.bashrc
echo "=== 所有工具安装完成 ==="
echo "重新加载配置: source ~/.bashrc"
echo "可用工作流命令:"
echo " dev_workflow - 开发工作流"
echo " sys_check - 系统检查"
echo " code_search_workflow - 代码搜索"
echo " file_management - 文件管理"
echo " quick_nav - 快速导航"
echo " tool_status - 工具状态检查"
工具关系与工作流程图
总结
通过安装和配置这10个命令行工具,你的 Linux 终端体验将得到质的提升:
效率提升亮点
- 搜索效率:fzf + fd + ripgrep 组合实现毫秒级搜索
- 文件浏览:exa 提供彩色、分栏、树状显示
- 代码阅读:bat 提供语法高亮和 Git 集成
- 系统监控:htop + dust 实时监控系统和磁盘
- 快速导航:zoxide 学习你的习惯,智能跳转
- Git 操作:lazygit 让 Git 操作变得直观简单
- 学习帮助:tldr 提供实用的命令示例
使用建议
- 渐进式学习:每周掌握1-2个工具,逐步整合到工作流中
- 个性化配置:根据个人习惯调整颜色、快捷键等配置
- 组合使用:学会工具间的配合,如 fzf + bat 预览文件
- 定期更新:这些工具活跃开发,定期更新获得新功能
现在重新加载配置,开始享受高效的命令行体验:
bash
source ~/.bashrc
tool_status # 检查所有工具状态