cli-productivity

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CLI Productivity Skill

CLI效率提升技巧

Master essential CLI tools and shell patterns for efficient terminal workflows. This skill covers modern replacements for traditional Unix tools, fuzzy finding, pipeline patterns, and shell customization.
掌握提升终端工作流效率的必备CLI工具与Shell使用模式。本技巧涵盖传统Unix工具的现代替代方案、模糊查找、管道模式以及Shell自定义配置。

When to Use This Skill

适用场景

USE when:

适用情况:

  • Building efficient terminal workflows
  • Processing text and JSON data
  • Searching codebases quickly
  • Navigating file systems efficiently
  • Automating repetitive tasks
  • Creating shell functions and aliases
  • Building interactive scripts
  • 构建高效的终端工作流
  • 处理文本与JSON数据
  • 快速搜索代码库
  • 高效导航文件系统
  • 自动化重复任务
  • 创建Shell函数与别名
  • 编写交互式脚本

DON'T USE when:

不适用情况:

  • GUI-based workflows are more appropriate
  • Processing binary data (use specialized tools)
  • Complex data analysis (use Python/Pandas)
  • Tasks requiring visual feedback
  • GUI工作流更合适的场景
  • 处理二进制数据(使用专用工具)
  • 复杂数据分析(使用Python/Pandas)
  • 需要视觉反馈的任务

Prerequisites

前置准备

Installation

安装步骤

macOS (Homebrew):
bash
undefined
macOS(Homebrew):
bash
undefined

Essential modern tools

Essential modern tools

brew install jq # JSON processor brew install fzf # Fuzzy finder brew install ripgrep # Fast grep (rg) brew install fd # Fast find brew install bat # Better cat brew install exa # Better ls (or eza) brew install zoxide # Smart cd brew install starship # Shell prompt brew install tmux # Terminal multiplexer
brew install jq # JSON processor brew install fzf # Fuzzy finder brew install ripgrep # Fast grep (rg) brew install fd # Fast find brew install bat # Better cat brew install exa # Better ls (or eza) brew install zoxide # Smart cd brew install starship # Shell prompt brew install tmux # Terminal multiplexer

Install fzf keybindings

Install fzf keybindings

$(brew --prefix)/opt/fzf/install

**Linux (Ubuntu/Debian):**
```bash
$(brew --prefix)/opt/fzf/install

**Linux(Ubuntu/Debian):**
```bash

Update package list

Update package list

sudo apt-get update
sudo apt-get update

Install from apt (may be older versions)

Install from apt (may be older versions)

sudo apt-get install -y jq fzf ripgrep fd-find bat
sudo apt-get install -y jq fzf ripgrep fd-find bat

Note: fd is 'fdfind' on Debian/Ubuntu

Note: fd is 'fdfind' on Debian/Ubuntu

sudo ln -s $(which fdfind) /usr/local/bin/fd
sudo ln -s $(which fdfind) /usr/local/bin/fd

bat may be 'batcat' on older systems

bat may be 'batcat' on older systems

sudo ln -s $(which batcat) /usr/local/bin/bat
sudo ln -s $(which batcat) /usr/local/bin/bat

Install exa/eza

Install exa/eza

sudo apt-get install -y exa # or: cargo install eza
sudo apt-get install -y exa # or: cargo install eza

Install zoxide

Install zoxide

Install starship

Install starship


**Arch Linux:**
```bash
sudo pacman -S jq fzf ripgrep fd bat exa zoxide starship tmux
Verification:
bash
undefined

**Arch Linux:**
```bash
sudo pacman -S jq fzf ripgrep fd bat exa zoxide starship tmux
验证安装:
bash
undefined

Verify installations

Verify installations

for cmd in jq fzf rg fd bat exa zoxide starship; do command -v $cmd && echo "$cmd: OK" || echo "$cmd: NOT FOUND" done
undefined
for cmd in jq fzf rg fd bat exa zoxide starship; do command -v $cmd && echo "$cmd: OK" || echo "$cmd: NOT FOUND" done
undefined

Core Capabilities

核心功能

1. jq - JSON Processing

1. jq - JSON处理工具

Basic Operations:
bash
undefined
基础操作:
bash
undefined

Pretty print JSON

Pretty print JSON

echo '{"name":"John","age":30}' | jq '.'
echo '{"name":"John","age":30}' | jq '.'

Extract field

Extract field

curl -s https://api.github.com/repos/nodejs/node | jq '.stargazers_count'
curl -s https://api.github.com/repos/nodejs/node | jq '.stargazers_count'

Filter arrays

Filter arrays

echo '[1,2,3,4,5]' | jq '.[] | select(. > 2)'
echo '[1,2,3,4,5]' | jq '.[] | select(. > 2)'

Transform data

Transform data

echo '{"first":"John","last":"Doe"}' | jq '{fullName: (.first + " " + .last)}'

**Common jq Patterns:**
```bash
echo '{"first":"John","last":"Doe"}' | jq '{fullName: (.first + " " + .last)}'

**常用jq模式:**
```bash

Extract multiple fields

Extract multiple fields

jq '{name: .name, stars: .stargazers_count}'
jq '{name: .name, stars: .stargazers_count}'

Array operations

Array operations

jq '.items | length' # Count items jq '.items | first' # First item jq '.items | last' # Last item jq '.items[0:5]' # Slice first 5
jq '.items | length' # Count items jq '.items | first' # First item jq '.items | last' # Last item jq '.items[0:5]' # Slice first 5

Filtering

Filtering

jq '.[] | select(.status == "active")' jq '.[] | select(.count > 100)' jq '.[] | select(.name | contains("test"))'
jq '.[] | select(.status == "active")' jq '.[] | select(.count > 100)' jq '.[] | select(.name | contains("test"))'

Sorting

Sorting

jq 'sort_by(.date)' jq 'sort_by(.date) | reverse'
jq 'sort_by(.date)' jq 'sort_by(.date) | reverse'

Grouping

Grouping

jq 'group_by(.category)' jq 'group_by(.category) | map({key: .[0].category, count: length})'
jq 'group_by(.category)' jq 'group_by(.category) | map({key: .[0].category, count: length})'

Mapping

Mapping

jq '.[] | {id, name}' jq 'map({id: .id, upper_name: (.name | ascii_upcase)})'

**Shell Functions for jq:**
```bash
jq '.[] | {id, name}' jq 'map({id: .id, upper_name: (.name | ascii_upcase)})'

**jq相关Shell函数:**
```bash

Pretty print JSON file

Pretty print JSON file

jqp() { jq '.' "$1" | bat --language json }
jqp() { jq '.' "$1" | bat --language json }

Extract field from JSON file

Extract field from JSON file

jqf() { local file="$1" local field="$2" jq -r ".$field" "$file" }
jqf() { local file="$1" local field="$2" jq -r ".$field" "$file" }

Count items in JSON array

Count items in JSON array

jqcount() { jq 'if type == "array" then length else 1 end' "$1" }
jqcount() { jq 'if type == "array" then length else 1 end' "$1" }

Filter JSON by field value

Filter JSON by field value

jqfilter() { local file="$1" local field="$2" local value="$3" jq --arg val "$value" ".[] | select(.$field == $val)" "$file" }
undefined
jqfilter() { local file="$1" local field="$2" local value="$3" jq --arg val "$value" ".[] | select(.$field == $val)" "$file" }
undefined

2. fzf - Fuzzy Finder

2. fzf - 模糊查找工具

Basic Usage:
bash
undefined
基础用法:
bash
undefined

Find and edit file

Find and edit file

vim $(fzf)
vim $(fzf)

Find with preview

Find with preview

fzf --preview 'bat --color=always {}'
fzf --preview 'bat --color=always {}'

Multi-select

Multi-select

fzf --multi
fzf --multi

Filter with query

Filter with query

echo -e "apple\nbanana\norange" | fzf --query "an"

**fzf Configuration:**
```bash
echo -e "apple\nbanana\norange" | fzf --query "an"

**fzf配置:**
```bash

Add to ~/.bashrc or ~/.zshrc

Add to ~/.bashrc or ~/.zshrc

Default options

Default options

export FZF_DEFAULT_OPTS=' --height 40% --layout=reverse --border --preview-window=right:50%:wrap --bind=ctrl-d:preview-page-down --bind=ctrl-u:preview-page-up '
export FZF_DEFAULT_OPTS=' --height 40% --layout=reverse --border --preview-window=right:50%:wrap --bind=ctrl-d:preview-page-down --bind=ctrl-u:preview-page-up '

Use fd for faster file finding

Use fd for faster file finding

export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git' export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" export FZF_ALT_C_COMMAND='fd --type d --hidden --follow --exclude .git'
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git' export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" export FZF_ALT_C_COMMAND='fd --type d --hidden --follow --exclude .git'

Preview settings

Preview settings

export FZF_CTRL_T_OPTS='--preview "bat --color=always --style=numbers --line-range=:500 {}"' export FZF_ALT_C_OPTS='--preview "exa --tree --level=2 --color=always {}"'

**Powerful fzf Functions:**
```bash
export FZF_CTRL_T_OPTS='--preview "bat --color=always --style=numbers --line-range=:500 {}"' export FZF_ALT_C_OPTS='--preview "exa --tree --level=2 --color=always {}"'

**实用fzf函数:**
```bash

Fuzzy edit file

Fuzzy edit file

fe() { local file file=$(fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }
fe() { local file file=$(fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }

Fuzzy cd into directory

Fuzzy cd into directory

fcd() { local dir dir=$(fd --type d --hidden --follow --exclude .git | fzf --preview 'exa --tree --level=2 --color=always {}') [[ -n "$dir" ]] && cd "$dir" }
fcd() { local dir dir=$(fd --type d --hidden --follow --exclude .git | fzf --preview 'exa --tree --level=2 --color=always {}') [[ -n "$dir" ]] && cd "$dir" }

Fuzzy kill process

Fuzzy kill process

fkill() { local pid pid=$(ps aux | sed 1d | fzf --multi | awk '{print $2}') [[ -n "$pid" ]] && echo "$pid" | xargs kill -9 }
fkill() { local pid pid=$(ps aux | sed 1d | fzf --multi | awk '{print $2}') [[ -n "$pid" ]] && echo "$pid" | xargs kill -9 }

Fuzzy git checkout branch

Fuzzy git checkout branch

fco() { local branch branch=$(git branch -a --color=always | grep -v '/HEAD' | fzf --ansi | sed 's/^[* ]*//' | sed 's#remotes/origin/##') [[ -n "$branch" ]] && git checkout "$branch" }
fco() { local branch branch=$(git branch -a --color=always | grep -v '/HEAD' | fzf --ansi | sed 's/^[* ]*//' | sed 's#remotes/origin/##') [[ -n "$branch" ]] && git checkout "$branch" }

Fuzzy git log

Fuzzy git log

flog() { git log --oneline --color=always | fzf --ansi --preview 'git show --color=always {1}' | awk '{print $1}' }
flog() { git log --oneline --color=always | fzf --ansi --preview 'git show --color=always {1}' | awk '{print $1}' }

Fuzzy history search

Fuzzy history search

fh() { local cmd cmd=$(history | fzf --tac | sed 's/^[ ][0-9][ ]*//') [[ -n "$cmd" ]] && eval "$cmd" }
fh() { local cmd cmd=$(history | fzf --tac | sed 's/^[ ][0-9][ ]*//') [[ -n "$cmd" ]] && eval "$cmd" }

Fuzzy environment variable

Fuzzy environment variable

fenv() { local var var=$(env | fzf | cut -d= -f1) [[ -n "$var" ]] && echo "${!var}" }
fenv() { local var var=$(env | fzf | cut -d= -f1) [[ -n "$var" ]] && echo "${!var}" }

Fuzzy docker container

Fuzzy docker container

fdocker() { local container container=$(docker ps --format '{{.Names}}\t{{.Image}}\t{{.Status}}' | fzf | awk '{print $1}') [[ -n "$container" ]] && docker exec -it "$container" sh }
undefined
fdocker() { local container container=$(docker ps --format '{{.Names}}\t{{.Image}}\t{{.Status}}' | fzf | awk '{print $1}') [[ -n "$container" ]] && docker exec -it "$container" sh }
undefined

3. ripgrep (rg) - Fast Search

3. ripgrep (rg) - 快速搜索工具

Basic Usage:
bash
undefined
基础用法:
bash
undefined

Search for pattern

Search for pattern

rg "function"
rg "function"

Case insensitive

Case insensitive

rg -i "error"
rg -i "error"

Show line numbers

Show line numbers

rg -n "TODO"
rg -n "TODO"

Search specific file types

Search specific file types

rg --type py "import" rg -t js "require"
rg --type py "import" rg -t js "require"

Exclude patterns

Exclude patterns

rg "pattern" --glob '!*.min.js' rg "pattern" --glob '!node_modules'

**Advanced ripgrep:**
```bash
rg "pattern" --glob '!*.min.js' rg "pattern" --glob '!node_modules'

**进阶ripgrep用法:**
```bash

Context lines

Context lines

rg -C 3 "error" # 3 lines before and after rg -B 2 "error" # 2 lines before rg -A 2 "error" # 2 lines after
rg -C 3 "error" # 3 lines before and after rg -B 2 "error" # 2 lines before rg -A 2 "error" # 2 lines after

Fixed strings (no regex)

Fixed strings (no regex)

rg -F "func()"
rg -F "func()"

Word boundaries

Word boundaries

rg -w "log" # Match "log" not "logging"
rg -w "log" # Match "log" not "logging"

Multiple patterns

Multiple patterns

rg -e "pattern1" -e "pattern2"
rg -e "pattern1" -e "pattern2"

Files matching pattern

Files matching pattern

rg -l "TODO" # List files only rg -c "TODO" # Count matches per file
rg -l "TODO" # List files only rg -c "TODO" # Count matches per file

Inverse match

Inverse match

rg -v "DEBUG" # Lines NOT containing DEBUG
rg -v "DEBUG" # Lines NOT containing DEBUG

Replace

Replace

rg "old" --replace "new"
rg "old" --replace "new"

JSON output

JSON output

rg --json "pattern" | jq '.'
rg --json "pattern" | jq '.'

Statistics

Statistics

rg --stats "pattern"

**ripgrep Functions:**
```bash
rg --stats "pattern"

**ripgrep相关函数:**
```bash

Search and preview with fzf

Search and preview with fzf

rgs() { rg --color=always --line-number "$1" | fzf --ansi --preview 'bat --color=always $(echo {} | cut -d: -f1) --highlight-line $(echo {} | cut -d: -f2)' }
rgs() { rg --color=always --line-number "$1" | fzf --ansi --preview 'bat --color=always $(echo {} | cut -d: -f1) --highlight-line $(echo {} | cut -d: -f2)' }

Search and open in editor

Search and open in editor

rge() { local selection selection=$(rg --color=always --line-number "$1" | fzf --ansi) if [[ -n "$selection" ]]; then local file=$(echo "$selection" | cut -d: -f1) local line=$(echo "$selection" | cut -d: -f2) ${EDITOR:-vim} "+$line" "$file" fi }
rge() { local selection selection=$(rg --color=always --line-number "$1" | fzf --ansi) if [[ -n "$selection" ]]; then local file=$(echo "$selection" | cut -d: -f1) local line=$(echo "$selection" | cut -d: -f2) ${EDITOR:-vim} "+$line" "$file" fi }

Search TODOs

Search TODOs

todos() { rg --color=always "TODO|FIXME|HACK|XXX" "${1:-.}" | fzf --ansi }
todos() { rg --color=always "TODO|FIXME|HACK|XXX" "${1:-.}" | fzf --ansi }

Search function definitions

Search function definitions

funcs() { rg --color=always "^(def |function |async function |const .* = |class )" "${1:-.}" | fzf --ansi }
undefined
funcs() { rg --color=always "^(def |function |async function |const .* = |class )" "${1:-.}" | fzf --ansi }
undefined

4. fd - Fast Find

4. fd - 快速文件查找工具

Basic Usage:
bash
undefined
基础用法:
bash
undefined

Find files by name

Find files by name

fd "readme"
fd "readme"

Find with extension

Find with extension

fd -e md fd -e py -e js
fd -e md fd -e py -e js

Find directories

Find directories

fd -t d "src"
fd -t d "src"

Find files

Find files

fd -t f "config"
fd -t f "config"

Exclude patterns

Exclude patterns

fd -E node_modules -E .git
fd -E node_modules -E .git

Hidden files

Hidden files

fd -H "config"
fd -H "config"

Execute command on results

Execute command on results

fd -e log -x rm {} fd -e py -x wc -l {}

**fd Functions:**
```bash
fd -e log -x rm {} fd -e py -x wc -l {}

**fd相关函数:**
```bash

Find and preview

Find and preview

fdp() { fd "$@" | fzf --preview 'bat --color=always {} 2>/dev/null || exa --tree --level=2 --color=always {}' }
fdp() { fd "$@" | fzf --preview 'bat --color=always {} 2>/dev/null || exa --tree --level=2 --color=always {}' }

Find and edit

Find and edit

fde() { local file file=$(fd -t f "$@" | fzf --preview 'bat --color=always {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }
fde() { local file file=$(fd -t f "$@" | fzf --preview 'bat --color=always {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }

Find large files

Find large files

fdlarge() { local size="${1:-100M}" fd -t f -S +"$size" | xargs ls -lh | sort -k5 -h }
fdlarge() { local size="${1:-100M}" fd -t f -S +"$size" | xargs ls -lh | sort -k5 -h }

Find recent files

Find recent files

fdrecent() { local days="${1:-7}" fd -t f --changed-within "${days}d" }
fdrecent() { local days="${1:-7}" fd -t f --changed-within "${days}d" }

Find duplicates by name

Find duplicates by name

fddup() { fd -t f | sort | uniq -d }
undefined
fddup() { fd -t f | sort | uniq -d }
undefined

5. bat - Better cat

5. bat - 增强版查看工具

Basic Usage:
bash
undefined
基础用法:
bash
undefined

Syntax highlighted output

Syntax highlighted output

bat file.py
bat file.py

Show line numbers

Show line numbers

bat -n file.py
bat -n file.py

Show all non-printable chars

Show all non-printable chars

bat -A file.py
bat -A file.py

Multiple files

Multiple files

bat file1.py file2.py
bat file1.py file2.py

Plain output (no decorations)

Plain output (no decorations)

bat -p file.py
bat -p file.py

Specific language

Specific language

bat -l json data.txt
bat -l json data.txt

Diff two files

Diff two files

bat --diff file1 file2

**bat Configuration:**
```bash
bat --diff file1 file2

**bat配置:**
```bash

Add to ~/.bashrc or ~/.zshrc

Add to ~/.bashrc or ~/.zshrc

Set bat as default pager

Set bat as default pager

export MANPAGER="sh -c 'col -bx | bat -l man -p'" export PAGER="bat"
export MANPAGER="sh -c 'col -bx | bat -l man -p'" export PAGER="bat"

Bat theme

Bat theme

export BAT_THEME="TwoDark"
export BAT_THEME="TwoDark"

Bat style

Bat style

export BAT_STYLE="numbers,changes,header"

**bat Aliases:**
```bash
export BAT_STYLE="numbers,changes,header"

**bat别名:**
```bash

Replace cat with bat

Replace cat with bat

alias cat='bat --paging=never'
alias cat='bat --paging=never'

Preview alias for fzf

Preview alias for fzf

alias preview='fzf --preview "bat --color=always {}"'
alias preview='fzf --preview "bat --color=always {}"'

Pretty print JSON

Pretty print JSON

alias json='bat -l json'
alias json='bat -l json'

Pretty print YAML

Pretty print YAML

alias yaml='bat -l yaml'
alias yaml='bat -l yaml'

Diff with bat

Diff with bat

alias diff='bat --diff'
undefined
alias diff='bat --diff'
undefined

6. exa/eza - Better ls

6. exa/eza - 增强版列表工具

Basic Usage:
bash
undefined
基础用法:
bash
undefined

Basic list

Basic list

exa
exa

Long format

Long format

exa -l
exa -l

All files including hidden

All files including hidden

exa -la
exa -la

Tree view

Tree view

exa --tree exa --tree --level=2
exa --tree exa --tree --level=2

Sort by modified

Sort by modified

exa -l --sort=modified
exa -l --sort=modified

With git status

With git status

exa -l --git
exa -l --git

Group directories first

Group directories first

exa -l --group-directories-first
exa -l --group-directories-first

Icons

Icons

exa -l --icons

**exa Aliases:**
```bash
exa -l --icons

**exa别名:**
```bash

Add to ~/.bashrc or ~/.zshrc

Add to ~/.bashrc or ~/.zshrc

Replace ls with exa

Replace ls with exa

alias ls='exa --group-directories-first' alias ll='exa -l --group-directories-first --git' alias la='exa -la --group-directories-first --git' alias lt='exa --tree --level=2' alias lta='exa --tree --level=2 -a'
alias ls='exa --group-directories-first' alias ll='exa -l --group-directories-first --git' alias la='exa -la --group-directories-first --git' alias lt='exa --tree --level=2' alias lta='exa --tree --level=2 -a'

With icons (if supported)

With icons (if supported)

alias li='exa -l --icons --group-directories-first --git'
undefined
alias li='exa -l --icons --group-directories-first --git'
undefined

7. zoxide - Smart cd

7. zoxide - 智能目录跳转工具

Basic Usage:
bash
undefined
基础用法:
bash
undefined

Initialize (add to shell rc)

Initialize (add to shell rc)

eval "$(zoxide init bash)" # or zsh
eval "$(zoxide init bash)" # or zsh

Use z instead of cd

Use z instead of cd

z projects # Jump to most frequent/recent match z pro # Partial match
z projects # Jump to most frequent/recent match z pro # Partial match

Interactive selection

Interactive selection

zi # Opens fzf for selection
zi # Opens fzf for selection

Add directory manually

Add directory manually

zoxide add /path/to/dir
zoxide add /path/to/dir

Query database

Query database

zoxide query projects zoxide query -l # List all entries

**zoxide Configuration:**
```bash
zoxide query projects zoxide query -l # List all entries

**zoxide配置:**
```bash

Add to ~/.bashrc or ~/.zshrc

Add to ~/.bashrc or ~/.zshrc

Initialize zoxide

Initialize zoxide

eval "$(zoxide init bash --cmd cd)" # Replace cd
eval "$(zoxide init bash --cmd cd)" # Replace cd

Or use custom command

Or use custom command

eval "$(zoxide init bash --cmd j)" # Use 'j' for jump
undefined
eval "$(zoxide init bash --cmd j)" # Use 'j' for jump
undefined

8. Shell Aliases and Functions

8. Shell别名与自定义函数

Essential Aliases:
bash
undefined
必备别名:
bash
undefined

Navigation

Navigation

alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..' alias ~='cd ~' alias -- -='cd -'
alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..' alias ~='cd ~' alias -- -='cd -'

Safety

Safety

alias rm='rm -i' alias mv='mv -i' alias cp='cp -i'
alias rm='rm -i' alias mv='mv -i' alias cp='cp -i'

Shortcuts

Shortcuts

alias c='clear' alias h='history' alias q='exit' alias v='vim' alias e='${EDITOR:-vim}'
alias c='clear' alias h='history' alias q='exit' alias v='vim' alias e='${EDITOR:-vim}'

Git shortcuts

Git shortcuts

alias g='git' alias gs='git status' alias ga='git add' alias gc='git commit' alias gp='git push' alias gl='git log --oneline -20' alias gd='git diff' alias gb='git branch' alias gco='git checkout'
alias g='git' alias gs='git status' alias ga='git add' alias gc='git commit' alias gp='git push' alias gl='git log --oneline -20' alias gd='git diff' alias gb='git branch' alias gco='git checkout'

Docker shortcuts

Docker shortcuts

alias d='docker' alias dc='docker compose' alias dps='docker ps' alias dimg='docker images' alias dlog='docker logs -f'
alias d='docker' alias dc='docker compose' alias dps='docker ps' alias dimg='docker images' alias dlog='docker logs -f'

Common directories

Common directories

alias proj='cd ~/projects' alias docs='cd ~/Documents' alias dl='cd ~/Downloads'

**Utility Functions:**
```bash
alias proj='cd ~/projects' alias docs='cd ~/Documents' alias dl='cd ~/Downloads'

**实用函数:**
```bash

Create directory and cd into it

Create directory and cd into it

mkcd() { mkdir -p "$1" && cd "$1" }
mkcd() { mkdir -p "$1" && cd "$1" }

Extract any archive

Extract any archive

extract() { if [[ -f "$1" ]]; then case "$1" in *.tar.bz2) tar xjf "$1" ;; *.tar.gz) tar xzf "$1" ;; *.tar.xz) tar xJf "$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" ;; esac else echo "'$1' is not a valid file" fi }
extract() { if [[ -f "$1" ]]; then case "$1" in *.tar.bz2) tar xjf "$1" ;; *.tar.gz) tar xzf "$1" ;; *.tar.xz) tar xJf "$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" ;; esac else echo "'$1' is not a valid file" fi }

Get public IP

Get public IP

myip() { curl -s https://ifconfig.me }
myip() { curl -s https://ifconfig.me }

Weather

Weather

weather() { curl -s "wttr.in/${1:-}" }
weather() { curl -s "wttr.in/${1:-}" }

Quick note

Quick note

note() { local notes_dir="${NOTES_DIR:-$HOME/notes}" local date=$(date +%Y-%m-%d) mkdir -p "$notes_dir" ${EDITOR:-vim} "$notes_dir/$date.md" }
note() { local notes_dir="${NOTES_DIR:-$HOME/notes}" local date=$(date +%Y-%m-%d) mkdir -p "$notes_dir" ${EDITOR:-vim} "$notes_dir/$date.md" }

Serve current directory

Serve current directory

serve() { local port="${1:-8000}" python -m http.server "$port" }
serve() { local port="${1:-8000}" python -m http.server "$port" }

Show disk usage for directory

Show disk usage for directory

duh() { du -h "${1:-.}" | sort -h | tail -20 }
duh() { du -h "${1:-.}" | sort -h | tail -20 }

Find process by name

Find process by name

psg() { ps aux | grep -v grep | grep -i "$1" }
undefined
psg() { ps aux | grep -v grep | grep -i "$1" }
undefined

Integration Examples

集成示例

1. Complete Shell Configuration

1. 完整Shell配置

~/.bashrc or ~/.zshrc:
bash
undefined
~/.bashrc 或 ~/.zshrc:
bash
undefined

═══════════════════════════════════════════════════════════════

═══════════════════════════════════════════════════════════════

CLI Productivity Configuration

CLI Productivity Configuration

═══════════════════════════════════════════════════════════════

═══════════════════════════════════════════════════════════════

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

Environment

Environment

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

export EDITOR="vim" export VISUAL="$EDITOR" export PAGER="bat" export MANPAGER="sh -c 'col -bx | bat -l man -p'"
export EDITOR="vim" export VISUAL="$EDITOR" export PAGER="bat" export MANPAGER="sh -c 'col -bx | bat -l man -p'"

XDG Base Directory

XDG Base Directory

export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

History

History

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

HISTSIZE=50000 HISTFILESIZE=50000 HISTCONTROL=ignoreboth:erasedups shopt -s histappend
HISTSIZE=50000 HISTFILESIZE=50000 HISTCONTROL=ignoreboth:erasedups shopt -s histappend

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

fzf Configuration

fzf Configuration

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git' export FZF_DEFAULT_OPTS=' --height 40% --layout=reverse --border --preview-window=right:50%:wrap ' export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" export FZF_CTRL_T_OPTS='--preview "bat --color=always --style=numbers --line-range=:500 {}"' export FZF_ALT_C_COMMAND='fd --type d --hidden --follow --exclude .git' export FZF_ALT_C_OPTS='--preview "exa --tree --level=2 --color=always {}"'
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git' export FZF_DEFAULT_OPTS=' --height 40% --layout=reverse --border --preview-window=right:50%:wrap ' export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" export FZF_CTRL_T_OPTS='--preview "bat --color=always --style=numbers --line-range=:500 {}"' export FZF_ALT_C_COMMAND='fd --type d --hidden --follow --exclude .git' export FZF_ALT_C_OPTS='--preview "exa --tree --level=2 --color=always {}"'

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

Tool Initialization

Tool Initialization

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

fzf keybindings

fzf keybindings

[ -f ~/.fzf.bash ] && source ~/.fzf.bash
[ -f ~/.fzf.bash ] && source ~/.fzf.bash

zoxide

zoxide

eval "$(zoxide init bash)"
eval "$(zoxide init bash)"

starship prompt

starship prompt

eval "$(starship init bash)"
eval "$(starship init bash)"

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

Aliases

Aliases

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

Modern replacements

Modern replacements

alias ls='exa --group-directories-first' alias ll='exa -l --group-directories-first --git' alias la='exa -la --group-directories-first --git' alias lt='exa --tree --level=2' alias cat='bat --paging=never' alias grep='rg' alias find='fd'
alias ls='exa --group-directories-first' alias ll='exa -l --group-directories-first --git' alias la='exa -la --group-directories-first --git' alias lt='exa --tree --level=2' alias cat='bat --paging=never' alias grep='rg' alias find='fd'

Navigation

Navigation

alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..'
alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..'

Git

Git

alias g='git' alias gs='git status' alias ga='git add' alias gc='git commit' alias gp='git push' alias gl='git log --oneline -20' alias gd='git diff'
alias g='git' alias gs='git status' alias ga='git add' alias gc='git commit' alias gp='git push' alias gl='git log --oneline -20' alias gd='git diff'

Docker

Docker

alias d='docker' alias dc='docker compose' alias dps='docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"'
alias d='docker' alias dc='docker compose' alias dps='docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"'

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

Functions

Functions

─────────────────────────────────────────────────────────────────

─────────────────────────────────────────────────────────────────

Fuzzy edit

Fuzzy edit

fe() { local file file=$(fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }
fe() { local file file=$(fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }

Fuzzy cd

Fuzzy cd

fcd() { local dir dir=$(fd --type d | fzf --preview 'exa --tree --level=2 --color=always {}') [[ -n "$dir" ]] && cd "$dir" }
fcd() { local dir dir=$(fd --type d | fzf --preview 'exa --tree --level=2 --color=always {}') [[ -n "$dir" ]] && cd "$dir" }

Search and edit

Search and edit

rge() { local selection selection=$(rg --color=always --line-number "$1" | fzf --ansi) if [[ -n "$selection" ]]; then local file=$(echo "$selection" | cut -d: -f1) local line=$(echo "$selection" | cut -d: -f2) ${EDITOR:-vim} "+$line" "$file" fi }
rge() { local selection selection=$(rg --color=always --line-number "$1" | fzf --ansi) if [[ -n "$selection" ]]; then local file=$(echo "$selection" | cut -d: -f1) local line=$(echo "$selection" | cut -d: -f2) ${EDITOR:-vim} "+$line" "$file" fi }

Create and cd

Create and cd

mkcd() { mkdir -p "$1" && cd "$1" }
undefined
mkcd() { mkdir -p "$1" && cd "$1" }
undefined

2. Data Processing Pipeline

2. 数据处理管道示例

bash
undefined
bash
undefined

Process JSON API response

Process JSON API response

curl -s 'https://api.github.com/users/torvalds/repos?per_page=100'
| jq '.[] | {name: .name, stars: .stargazers_count}'
| jq -s 'sort_by(.stars) | reverse | .[0:10]'
curl -s 'https://api.github.com/users/torvalds/repos?per_page=100'
| jq '.[] | {name: .name, stars: .stargazers_count}'
| jq -s 'sort_by(.stars) | reverse | .[0:10]'

Find large log files and show preview

Find large log files and show preview

fd -e log -S +10M
| fzf --preview 'tail -100 {}'
| xargs -I{} bat --line-range=:50 {}
fd -e log -S +10M
| fzf --preview 'tail -100 {}'
| xargs -I{} bat --line-range=:50 {}

Search code, preview matches, edit selected

Search code, preview matches, edit selected

rg --color=always -l "TODO"
| fzf --preview 'rg --color=always -C 3 "TODO" {}'
| xargs -o ${EDITOR:-vim}
rg --color=always -l "TODO"
| fzf --preview 'rg --color=always -C 3 "TODO" {}'
| xargs -o ${EDITOR:-vim}

Git log with diff preview

Git log with diff preview

git log --oneline --color=always
| fzf --ansi --preview 'git show --color=always {1}'
| awk '{print $1}'
| xargs git show
undefined
git log --oneline --color=always
| fzf --ansi --preview 'git show --color=always {1}'
| awk '{print $1}'
| xargs git show
undefined

3. Interactive Script Template

3. 交互式脚本模板

bash
#!/bin/bash
bash
#!/bin/bash

ABOUTME: Interactive CLI script using fzf and modern tools

ABOUTME: Interactive CLI script using fzf and modern tools

ABOUTME: Template for building interactive shell tools

ABOUTME: Template for building interactive shell tools

set -e
set -e

Colors

Colors

RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' CYAN='\033[0;36m' NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $"; } log_warn() { echo -e "${YELLOW}[WARN]${NC} $"; } log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' CYAN='\033[0;36m' NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $"; } log_warn() { echo -e "${YELLOW}[WARN]${NC} $"; } log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

Check dependencies

Check dependencies

check_deps() { local missing=() for cmd in fzf rg fd bat jq; do command -v "$cmd" >/dev/null || missing+=("$cmd") done
if [[ ${#missing[@]} -gt 0 ]]; then
    log_error "Missing dependencies: ${missing[*]}"
    exit 1
fi
}
check_deps() { local missing=() for cmd in fzf rg fd bat jq; do command -v "$cmd" >/dev/null || missing+=("$cmd") done
if [[ ${#missing[@]} -gt 0 ]]; then
    log_error "Missing dependencies: ${missing[*]}"
    exit 1
fi
}

Main menu using fzf

Main menu using fzf

main_menu() { local options=( "Search files" "Search content" "Edit config" "Run tests" "Exit" )
local selection
selection=$(printf '%s\n' "${options[@]}" | fzf --header="Select action:")

case "$selection" in
    "Search files") search_files ;;
    "Search content") search_content ;;
    "Edit config") edit_config ;;
    "Run tests") run_tests ;;
    "Exit") exit 0 ;;
esac
}
search_files() { local file file=$(fd --type f | fzf --preview 'bat --color=always {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }
search_content() { local query read -p "Search pattern: " query rge "$query" }
edit_config() { local configs=("/.bashrc" "/.vimrc" "~/.gitconfig") local config config=$(printf '%s\n' "${configs[@]}" | fzf --header="Select config:") [[ -n "$config" ]] && ${EDITOR:-vim} "${config/#~/$HOME}" }
run_tests() { log_info "Running tests..." # Add test command here }
main_menu() { local options=( "Search files" "Search content" "Edit config" "Run tests" "Exit" )
local selection
selection=$(printf '%s\n' "${options[@]}" | fzf --header="Select action:")

case "$selection" in
    "Search files") search_files ;;
    "Search content") search_content ;;
    "Edit config") edit_config ;;
    "Run tests") run_tests ;;
    "Exit") exit 0 ;;
esac
}
search_files() { local file file=$(fd --type f | fzf --preview 'bat --color=always {}') [[ -n "$file" ]] && ${EDITOR:-vim} "$file" }
search_content() { local query read -p "Search pattern: " query rge "$query" }
edit_config() { local configs=("/.bashrc" "/.vimrc" "~/.gitconfig") local config config=$(printf '%s\n' "${configs[@]}" | fzf --header="Select config:") [[ -n "$config" ]] && ${EDITOR:-vim} "${config/#~/$HOME}" }
run_tests() { log_info "Running tests..." # Add test command here }

Main

Main

check_deps while true; do main_menu done
undefined
check_deps while true; do main_menu done
undefined

Best Practices

最佳实践

1. Tool Selection Guidelines

1. 工具选择指南

TaskToolWhy
Find files by namefdFast, intuitive syntax
Find files by contentrgFaster than grep, better defaults
View filesbatSyntax highlighting, line numbers
List filesexaIcons, git status, tree view
Navigate directorieszoxideLearns your patterns
Interactive selectionfzfFuzzy matching, preview
Process JSONjqPowerful, composable
任务工具理由
按名称查找文件fd速度快,语法直观
按内容查找文件rg比grep更快,默认配置更优
查看文件内容bat支持语法高亮、行号显示
列出文件列表exa支持图标、Git状态、树形视图
导航目录zoxide学习你的使用习惯
交互式选择fzf模糊匹配、预览功能
处理JSON数据jq功能强大,支持组合使用

2. Performance Tips

2. 性能优化技巧

bash
undefined
bash
undefined

Use fd instead of find

Use fd instead of find

fd "pattern" # Instead of: find . -name "pattern"
fd "pattern" # Instead of: find . -name "pattern"

Use rg instead of grep

Use rg instead of grep

rg "pattern" # Instead of: grep -r "pattern" .
rg "pattern" # Instead of: grep -r "pattern" .

Limit search depth

Limit search depth

fd --max-depth 3 rg --max-depth 3
fd --max-depth 3 rg --max-depth 3

Exclude directories

Exclude directories

fd -E node_modules -E .git rg --glob '!node_modules'
undefined
fd -E node_modules -E .git rg --glob '!node_modules'
undefined

3. Shell Startup Optimization

3. Shell启动速度优化

bash
undefined
bash
undefined

Lazy load slow tools

Lazy load slow tools

nvm() { unset -f nvm [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" nvm "$@" }
nvm() { unset -f nvm [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" nvm "$@" }

Cache expensive operations

Cache expensive operations

_update_ps1_cache() { PS1_CACHE="$(expensive_command)" }
undefined
_update_ps1_cache() { PS1_CACHE="$(expensive_command)" }
undefined

Troubleshooting

故障排查

Common Issues

常见问题

fzf not finding files:
bash
undefined
fzf无法找到文件:
bash
undefined

Check FZF_DEFAULT_COMMAND

Check FZF_DEFAULT_COMMAND

echo $FZF_DEFAULT_COMMAND
echo $FZF_DEFAULT_COMMAND

Test fd directly

Test fd directly

fd --type f
fd --type f

Check for hidden files

Check for hidden files

fd -H

**Colors not working:**
```bash
fd -H

**颜色显示异常:**
```bash

Check terminal capabilities

Check terminal capabilities

echo $TERM
echo $TERM

Force color output

Force color output

export CLICOLOR_FORCE=1

**Slow shell startup:**
```bash
export CLICOLOR_FORCE=1

**Shell启动缓慢:**
```bash

Profile startup time

Profile startup time

time bash -i -c exit
time bash -i -c exit

Identify slow sources

Identify slow sources

for f in ~/.bashrc ~/.bash_profile; do echo "--- $f ---" time source "$f" done

**zoxide not working:**
```bash
for f in ~/.bashrc ~/.bash_profile; do echo "--- $f ---" time source "$f" done

**zoxide无法正常工作:**
```bash

Check initialization

Check initialization

type z
type z

Rebuild database

Rebuild database

zoxide import --from=z
undefined
zoxide import --from=z
undefined

Version History

版本历史

  • 1.0.0 (2026-01-17): Initial release
    • Core CLI tools coverage (jq, fzf, ripgrep, fd, bat, exa)
    • Shell aliases and functions
    • Pipeline patterns
    • Integration examples
    • Shell configuration templates

Use this skill to build efficient, productive terminal workflows with modern CLI tools!
  • 1.0.0(2026-01-17):初始版本
    • 覆盖核心CLI工具(jq、fzf、ripgrep、fd、bat、exa)
    • 包含Shell别名与自定义函数
    • 提供管道模式示例
    • 集成配置示例
    • Shell配置模板

使用本技巧,借助现代CLI工具构建高效、高生产力的终端工作流!