Linux命令行效率工具与技巧
Linux命令行效率工具与技巧
Linux命令行是开发者最强大的工具之一。本文将介绍提升命令行效率的各种工具和技巧。
Shell配置
1. Zsh + Oh My Zsh
安装配置
# 安装Zsh
sudo apt install zsh # Ubuntu/Debian
sudo yum install zsh # CentOS/RHEL
brew install zsh # macOS
# 设置默认Shell
chsh -s $(which zsh)
# 安装Oh My Zsh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
插件配置
# ~/.zshrc
plugins=(
git # Git别名和自动补全
z # 目录跳转
zsh-autosuggestions # 命令建议
zsh-syntax-highlighting # 语法高亮
docker # Docker补全
kubectl # Kubectl补全
npm # NPM补全
node # Node.js补全
python # Python补全
pip # Pip补全
sudo # 按两次Esc添加sudo
copypath # 复制路径
copyfile # 复制文件内容
extract # 解压任何格式
web-search # 网页搜索
)
# 安装额外插件
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
主题配置
# ~/.zshrc
ZSH_THEME="powerlevel10k/powerlevel10k"
# 安装Powerlevel10k
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
# 配置Powerlevel10k
p10k configure
2. Bash优化
# ~/.bashrc
# 历史记录优化
export HISTSIZE=100000
export HISTFILESIZE=100000
export HISTCONTROL=ignoreboth:erasedups
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "
shopt -s histappend
# 自动补全
bind 'set show-all-if-ambiguous on'
bind 'set completion-ignore-case on'
# 目录导航
shopt -s autocd
shopt -s cdspell
shopt -s dirspell
# 别名
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
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'
# 函数
mkcd() {
mkdir -p "$1" && cd "$1"
}
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
}
高效工具
1. 文件管理
fzf - 模糊查找
# 安装
brew install fzf
# 配置
# ~/.zshrc
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
# 使用
Ctrl+T # 查找文件
Ctrl+R # 查找历史命令
Alt+C # 查找目录
# 自定义函数
# 查找并编辑文件
fe() {
local files
IFS=$'\n' files=($(fzf-tmux --query="$1" --multi --select-1 --exit-0))
[[ -n "$files" ]] && ${EDITOR:-vim} "${files[@]}"
}
# 查找并进入目录
fd() {
local dir
dir=$(find ${1:-.} -path '*/\.*' -prune -o -type d -print 2> /dev/null | fzf +m) &&
cd "$dir"
}
# Git分支切换
fbr() {
local branches branch
branches=$(git branch --all | grep -v HEAD) &&
branch=$(echo "$branches" | fzf-tmux -d $(( 2 + $(wc -l <<< "$branches") )) +m) &&
git checkout $(echo "$branch" | sed "s/.* //" | sed "s#remotes/[^/]*/##")
}
ripgrep (rg) - 快速搜索
# 安装
brew install ripgrep
# 使用
rg "pattern" # 搜索文件内容
rg -i "pattern" # 忽略大小写
rg -l "pattern" # 只显示文件名
rg -t js "pattern" # 搜索特定类型文件
rg -g "*.js" "pattern" # 使用glob模式
rg --hidden "pattern" # 包含隐藏文件
rg -C 3 "pattern" # 显示上下文
rg -r "old" "new" # 替换
fd - 快速查找
# 安装
brew install fd
# 使用
fd "pattern" # 查找文件
fd -e js # 按扩展名查找
fd -t f # 只查找文件
fd -t d # 只查找目录
fd -H # 包含隐藏文件
fd -I # 不忽略.gitignore
fd -x rm # 执行命令
2. 文本处理
bat - 增强版cat
# 安装
brew install bat
# 使用
bat file.txt # 带语法高亮显示
bat -n file.txt # 显示行号
bat -r 10:20 file.txt # 显示特定行范围
bat -l python script.py # 指定语言
bat --diff file.txt # 显示Git差异
exa - 增强版ls
# 安装
brew install exa
# 使用
exa # 彩色列表
exa -l # 长格式
exa -la # 包含隐藏文件
exa -T # 树形显示
exa -T -L 2 # 限制深度
exa -l --git # 显示Git状态
exa -l --sort=modified # 按修改时间排序
exa -l --icons # 显示图标
tldr - 简化版man
# 安装
brew install tldr
# 使用
tldr tar # 查看tar常用命令
tldr git # 查看git常用命令
tldr -p linux du # 查看Linux平台命令
3. 系统监控
htop - 交互式进程查看
# 安装
brew install htop
# 使用
htop # 启动交互式界面
# F1-F10 各种功能
# / 搜索进程
# k 杀死进程
# t 树形显示
# u 按用户过滤
glances - 全能系统监控
# 安装
pip install glances
# 使用
glances # 启动监控
glances -w # Web界面模式
glances --export csv # 导出数据
ncdu - 磁盘使用分析
# 安装
brew install ncdu
# 使用
ncdu # 分析当前目录
ncdu /home # 分析指定目录
ncdu -x / # 不跨越文件系统
4. 网络工具
httpie - HTTP客户端
# 安装
brew install httpie
# 使用
http GET example.com
http POST api.example.com/users name=John age:=30
http -a username:password GET api.example.com/protected
http --download GET example.com/file.zip
curlie - curl美化版
# 安装
brew install curlie
# 使用
curlie get example.com
curlie post api.example.com/users -d '{"name":"John"}' -H 'Content-Type: application/json'
终端多路复用
1. Tmux配置
# ~/.tmux.conf
# 前缀键
unbind C-b
set -g prefix C-a
bind C-a send-prefix
# 基本设置
set -g mouse on
set -g history-limit 10000
set -g default-terminal "screen-256color"
set -ga terminal-overrides ",*256col*:Tc"
# 窗口和面板
bind | split-window -h
bind - split-window -v
unbind '"'
unbind %
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
bind -r H resize-pane -L 5
bind -r J resize-pane -D 5
bind -r K resize-pane -U 5
bind -r L resize-pane -R 5
# 状态栏
set -g status-bg colour234
set -g status-fg colour137
set -g status-left ''
set -g status-right '#[fg=colour233,bg=colour241,bold] %d/%m #[fg=colour233,bg=colour245,bold] %H:%M:%S '
# 窗口状态
setw -g window-status-current-format ' #I#[fg=colour250]:#[fg=colour255]#W#[fg=colour50]#F '
setw -g window-status-format ' #I#[fg=colour237]:#[fg=colour250]#W#[fg=colour244]#F '
# 复制模式
setw -g mode-keys vi
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi y send-keys -X copy-selection-and-cancel
Tmux常用命令
# 会话管理
tmux new -s mysession # 创建会话
tmux attach -t mysession # 附加到会话
tmux detach # 分离会话
tmux ls # 列出会话
tmux kill-session -t mysession # 关闭会话
# 窗口管理
Ctrl+a c # 创建窗口
Ctrl+a n # 下一个窗口
Ctrl+a p # 上一个窗口
Ctrl+a 0-9 # 切换到指定窗口
Ctrl+a , # 重命名窗口
Ctrl+a & # 关闭窗口
# 面板管理
Ctrl+a % # 垂直分割
Ctrl+a " # 水平分割
Ctrl+a o # 切换面板
Ctrl+a x # 关闭面板
Ctrl+a z # 最大化面板
2. Zellij(Tmux替代品)
# 安装
cargo install zellij
# 使用
zellij # 启动
zellij attach # 附加到会话
zellij list-sessions # 列出会话
# 快捷键
Ctrl+p # 面板模式
Ctrl+t # 标签模式
Ctrl+n # 调整大小模式
Ctrl+h # 移动模式
开发工具
1. Git增强
lazygit - TUI Git客户端
# 安装
brew install lazygit
# 使用
lazygit # 启动TUI界面
# 快捷键
# 1-5 切换面板
# a 暂存所有
# c 提交
# P 推送
# p 拉取
# n 新建分支
git-delta - Git差异美化
# 安装
brew install git-delta
# 配置
# ~/.gitconfig
[core]
pager = delta
[delta]
line-numbers = true
side-by-side = true
syntax-theme = Dracula
2. 编辑器
Neovim配置
-- ~/.config/nvim/init.lua
-- 插件管理器
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
vim.fn.system({
"git",
"clone",
"--filter=blob:none",
"https://github.com/folke/lazy.nvim.git",
"--branch=stable",
lazypath,
})
end
vim.opt.rtp:prepend(lazypath)
-- 插件
require("lazy").setup({
-- 主题
{ "dracula/vim", name = "dracula" },
-- 文件浏览器
{
"nvim-tree/nvim-tree.lua",
dependencies = { "nvim-tree/nvim-web-devicons" },
},
-- 模糊查找
{
"nvim-telescope/telescope.nvim",
dependencies = { "nvim-lua/plenary.nvim" },
},
-- 语法高亮
{
"nvim-treesitter/nvim-treesitter",
build = ":TSUpdate",
},
-- LSP
{ "neovim/nvim-lspconfig" },
-- 自动补全
{
"hrsh7th/nvim-cmp",
dependencies = {
"hrsh7th/cmp-nvim-lsp",
"hrsh7th/cmp-buffer",
"hrsh7th/cmp-path",
},
},
})
-- 基本设置
vim.opt.number = true
vim.opt.relativenumber = true
vim.opt.expandtab = true
vim.opt.shiftwidth = 2
vim.opt.tabstop = 2
vim.opt.smartindent = true
vim.opt.wrap = false
vim.opt.swapfile = false
vim.opt.backup = false
vim.opt.undofile = true
vim.opt.hlsearch = false
vim.opt.incsearch = true
vim.opt.termguicolors = true
vim.opt.scrolloff = 8
vim.opt.signcolumn = "yes"
-- 主题
vim.cmd("colorscheme dracula")
-- 快捷键
vim.g.mapleader = " "
vim.keymap.set("n", "<leader>pv", vim.cmd.Ex)
vim.keymap.set("n", "<leader>ff", "<cmd>Telescope find_files<cr>")
vim.keymap.set("n", "<leader>fg", "<cmd>Telescope live_grep<cr>")
vim.keymap.set("n", "<leader>fb", "<cmd>Telescope buffers<cr>")
脚本编写
1. 实用脚本
项目快速启动
#!/bin/bash
# dev-start.sh
PROJECT_DIR="$HOME/projects"
echo "Select project:"
project=$(ls -1 $PROJECT_DIR | fzf)
if [ -z "$project" ]; then
echo "No project selected"
exit 1
fi
cd "$PROJECT_DIR/$project"
# 检测项目类型并启动
if [ -f "docker-compose.yml" ]; then
docker-compose up -d
elif [ -f "package.json" ]; then
npm install && npm run dev
elif [ -f "requirements.txt" ]; then
source venv/bin/activate && python manage.py runserver
else
echo "Unknown project type"
fi
Git仓库批量操作
#!/bin/bash
# git-batch.sh
REPOS_DIR="$HOME/repos"
case "$1" in
pull)
for dir in $REPOS_DIR/*/; do
if [ -d "$dir/.git" ]; then
echo "Pulling $dir..."
(cd "$dir" && git pull)
fi
done
;;
status)
for dir in $REPOS_DIR/*/; do
if [ -d "$dir/.git" ]; then
echo "=== $dir ==="
(cd "$dir" && git status -s)
fi
done
;;
*)
echo "Usage: $0 {pull|status}"
exit 1
;;
esac
日志分析
#!/bin/bash
# log-analyzer.sh
LOG_FILE="$1"
if [ -z "$LOG_FILE" ]; then
echo "Usage: $0 <log-file>"
exit 1
fi
echo "=== Error Summary ==="
grep -i "error" "$LOG_FILE" | wc -l | xargs echo "Total errors:"
echo ""
echo "=== Top Error Types ==="
grep -i "error" "$LOG_FILE" | awk '{print $5}' | sort | uniq -c | sort -rn | head -10
echo ""
echo "=== Response Time Stats ==="
awk '/Response time/ {print $4}' "$LOG_FILE" | awk '
{sum+=$1; count++}
END {
print "Count:", count
print "Average:", sum/count "ms"
}'
2. 函数库
# ~/.bash_functions
# 颜色输出
red() { echo -e "\033[31m$*\033[0m"; }
green() { echo -e "\033[32m$*\033[0m"; }
yellow() { echo -e "\033[33m$*\033[0m"; }
blue() { echo -e "\033[34m$*\033[0m"; }
# 进度条
progress() {
local width=50
local percent=$1
local filled=$((width * percent / 100))
local empty=$((width - filled))
printf "\r["
printf "%${filled}s" | tr ' ' '='
printf "%${empty}s" | tr ' ' ' '
printf "] %d%%" "$percent"
}
# 计时器
timer() {
local seconds=$1
while [ $seconds -gt 0 ]; do
echo -ne "\rTime remaining: ${seconds}s"
sleep 1
((seconds--))
done
echo -e "\rTime's up! "
}
# 备份文件
backup() {
local file="$1"
local backup_name="${file}.backup.$(date +%Y%m%d_%H%M%S)"
cp -r "$file" "$backup_name"
echo "Backup created: $backup_name"
}
# 端口检查
check_port() {
local port=$1
if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null ; then
echo "Port $port is in use"
lsof -Pi :$port -sTCP:LISTEN
else
echo "Port $port is available"
fi
}
# 杀死占用端口的进程
kill_port() {
local port=$1
local pid=$(lsof -Pi :$port -sTCP:LISTEN -t)
if [ -n "$pid" ]; then
kill -9 $pid
echo "Killed process $pid on port $port"
else
echo "No process found on port $port"
fi
}
总结
Linux命令行效率提升的关键点:
- Shell配置:使用Zsh+Oh My Zsh提升交互体验
- 现代工具:用fzf、ripgrep、bat等工具替代传统命令
- 终端复用:使用Tmux管理多个会话和窗口
- 别名和函数:创建常用命令的快捷方式
- 脚本自动化:编写脚本处理重复任务
- 持续学习:探索新工具和技巧
通过合理配置和使用这些工具,可以大幅提升命令行工作效率。