Shell 函数
实用的 Shell 函数集合。
文件操作
bash
# 创建目录并进入
mkcd() {
mkdir -p "$1" && cd "$1"
}
# 快速备份
backup() {
cp "$1" "$1.bak.$(date +%Y%m%d%H%M%S)"
}
# 查找文件内容
findin() {
grep -rn "$1" .
}网络
bash
# 快速 HTTP 服务
serve() {
python3 -m http.server "${1:-8000}"
}
# 查看 IP
myip() {
curl -s ifconfig.me
}
# 测试端口
testport() {
nc -zv "$1" "$2"
}Git
bash
# 快速提交
git-commit() {
git add -A && git commit -m "$1"
}
# 快速推送
git-push() {
git add -A && git commit -m "${1:-update}" && git push
}
# 克隆并进入
clone() {
git clone "$1" && cd "$(basename "$1" .git)"
}系统
bash
# 查看端口占用
port() {
lsof -i :"$1"
}
# 杀掉端口进程
killport() {
lsof -ti :"$1" | xargs kill -9
}
# 查看进程树
pst() {
ps auxf
}开发
bash
# 创建 Python 虚拟环境
venv() {
python3 -m venv "${1:-venv}" && source "${1:-venv}/bin/activate"
}
# Node 项目初始化
npm-init() {
npm init -y && npm install
}解压
bash
# 通用解压函数
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 "Unknown format" ;;
esac
else
echo "File not found: $1"
fi
}使用方法
将以上函数添加到 ~/.bashrc 或 ~/.zshrc 文件末尾,然后运行:
bash
source ~/.bashrc # 或 source ~/.zshrc