Câu Lệnh DevOps và Bash Aliases sẽ giúp bạn cải thiện đáng kể tốc độ khi thao tác. Bạn biết vì sao không?
Tôi Đã Nhìn Một Senior Developer Gõ Một Lệnh. Nó Đã Thay Đổi Quan Điểm Của Tôi.
Vào tuần trước, tôi có nhờ anh Zai DevOps Leader hỗ trợ. Anh ấy cần kiểm tra trạng thái pod, chuyển đổi namespaces, lấy logs và khởi động lại một dịch vụ. Tôi đã mong đợi thấy anh ấy gõ những lệnh Kubernetes dài dòng đó.
Thay vào đó, anh ấy đã gõ:
, kns prod , kgp
klogs api-pod
, krestart api
.
Bốn lần gõ phím. Bốn giây. Vấn đề đã được giải quyết.
Anh zai cười bảo tôi. Tao đã không gõ full câu lệnh mấy năm nay rồi 😀
Thì ra là thế =))) cayyy đấy. Vậy thì mình cũng nên clone cái ý tưởng này nhỉ.
Git Shortcuts That Actually Matter
Bash Aliases đầu tiên là với git
# Quick status with colors alias gs='git status -s' # Add everything and commit in one line alias gac='git add . && git commit -m' # Push current branch alias gp='git push origin $(git branch --show-current)' # Pull with rebase (cleaner history) alias gpr='git pull --rebase' # Undo last commit but keep changes alias gundo='git reset --soft HEAD~1' # Show last 10 commits in pretty format alias glog='git log --oneline -10 --graph --decorate' # Delete merged branches alias gclean='git branch --merged | grep -v "\*\|main\|master\|develop" | xargs -n 1 git branch -d' # Quick stash with message alias gstash='git stash push -m' # Show what changed in last commit alias gshow='git show --stat' # Force push safely (checks for updates first) alias gpf='git push --force-with-lease'
Docker Speed One-Liners
Câu Lệnh DevOps thì không thể thiếu docker rồi. Đây là Bash Aliases tôi dùng.
# Stop all containers alias dstop='docker stop $(docker ps -q)' # Remove all containers alias drm='docker rm $(docker ps -aq)' # Remove all images alias drmi='docker rmi $(docker images -q)' # Clean everything (careful with this one!) alias dclean='docker system prune -af' # Get into running container quickly alias dexec='docker exec -it' # Show container logs with follow alias dlogs='docker logs -f' # Quick container stats alias dstats='docker stats --no-stream' # Build and run in one command dbr() { docker build -t $1 . && docker run -it $1; } # Remove dangling images alias ddangling='docker rmi $(docker images -f "dangling=true" -q)' # Quick MySQL container for testing alias mysql-test='docker run --rm -e MYSQL_ROOT_PASSWORD=root -p 3306:3306 mysql:8'
Kubernetes Shortcuts
Chưa thấy devops nào không dùng k8s :D. đây là Bash Aliases của k8s nhé:
# Short kubectl alias k='kubectl' # Get pods with wide output alias kgp='kubectl get pods -o wide' # Get all resources alias kga='kubectl get all' # Describe pod quickly alias kdp='kubectl describe pod' # Get pod logs alias klogs='kubectl logs -f' # Delete pod by name alias kdel='kubectl delete pod' # Get into pod shell kexec() { kubectl exec -it $1 -- /bin/bash; } # Port forward shortcut kpf() { kubectl port-forward $1 $2:$2; } # Get services alias kgs='kubectl get svc' # Apply and show what changed alias kapp='kubectl apply -f' # Get nodes with more info alias kgn='kubectl get nodes -o wide' # Switch namespace quickly kns() { kubectl config set-context --current --namespace=$1; } # Get current context alias kctx='kubectl config current-context' # Top pods (resource usage) alias ktop='kubectl top pods' # Get all pods in all namespaces alias kgpall='kubectl get pods --all-namespaces'
AWS CLI
Trong bộ các câu lệnh devops thì thằng aws cli này là thằng tôi nói luôn là tôi không bao giờ nhớ. Bash aliases thiết lập ban đầu gần như tiết kiệm được 90%.
# List all S3 buckets alias s3ls='aws s3 ls' # Sync folder to S3 (upload) s3up() { aws s3 sync $1 s3://$2 --delete; } # Download from S3 s3down() { aws s3 sync s3://$1 $2; } # List EC2 instances with key info alias ec2ls='aws ec2 describe-instances --query "Reservations[*].Instances[*].[InstanceId,State.Name,InstanceType,PublicIpAddress]" --output table' # Get AWS account ID alias awsid='aws sts get-caller-identity --query Account --output text' # List all regions alias awsregions='aws ec2 describe-regions --query "Regions[*].RegionName" --output text' # Quick CloudFormation stack status cfstatus() { aws cloudformation describe-stacks --stack-name $1 --query 'Stacks[0].StackStatus' --output text; } # List Lambda functions alias lambdals='aws lambda list-functions --query "Functions[*].[FunctionName,Runtime]" --output table' # Get RDS instances alias rdsls='aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier,DBInstanceStatus,Engine]" --output table'
Azure CLI Power Moves
# List all resource groups alias azrg='az group list -o table' # List VMs with status alias azvm='az vm list -d -o table' # Get subscription info alias azsub='az account show' # List all locations alias azloc='az account list-locations -o table' # Create resource group quickly azrgcreate() { az group create --name $1 --location $2; } # Delete resource group (be careful!) azrgdel() { az group delete --name $1 --yes --no-wait; } # List storage accounts alias azst='az storage account list -o table' # Get AKS credentials azaks() { az aks get-credentials --resource-group $1 --name $2; } # List app services alias azapp='az webapp list -o table'
System Monitoring Made Simple
Máy chủ của bạn đang chạy chậm. Thay vì chạy nhiều lệnh để kiểm tra CPU, bộ nhớ và mức sử dụng đĩa, bạn nhanh chóng gõ mem
, df
và cpu
để có cái nhìn tổng quát.
# Show disk usage in human format alias df='df -h' # Show directory sizes alias du='du -sh *' # Show memory usage clearly alias mem='free -h' # Show top 10 largest files alias big='du -a | sort -nr | head -10' # Show listening ports alias ports='netstat -tuln' # Show process tree alias pstree='ps auxf' # Kill process by name killp() { pkill -f $1; } # Show CPU info alias cpu='lscpu' # Show system info alias sysinfo='uname -a && uptime' # Monitor log files alias tailf='tail -f' # Show open files by process lsofp() { lsof -p $1; } # Find files larger than size findbig() { find . -size +$1 -type f -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'; }
File Operations
# Make directory and cd into it mkcd() { mkdir -p $1 && cd $1; } # Go back multiple directories alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..' # List files with details alias ll='ls -alF' alias la='ls -A' # Find files by name (case insensitive) findf() { find . -iname "*$1*"; } # Find and replace in files findreplace() { grep -rl "$1" . | xargs sed -i "s/$1/$2/g"; } # Archive and compress alias tarzip='tar -czf' # Extract any archive extract() { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar xjf $1 ;; *.tar.gz) tar xzf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) unrar e $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 }
Network Debugging Essentials
# Quick ping test alias pg='ping google.com' # Show external IP alias myip='curl -s https://ifconfig.me' # Show local network info alias localip='hostname -I' # Test if port is open testport() { nc -zv $1 $2; } # Download file quickly alias wget='wget -c' # Speed test alias speedtest='curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python -' # Show network connections alias netcon='ss -tuln' # Flush DNS (macOS) alias flushdns='sudo dscacheutil -flushcache' # Show routing table alias route='netstat -rn'
Search and Replace
# Find text in files findtext() { grep -r "$1" .; } # Find and count occurrences counttext() { grep -r "$1" . | wc -l; } # Case insensitive search findtexti() { grep -ri "$1" .; } # Search in specific file types findpy() { find . -name "*.py" -exec grep -l "$1" {} \;; } # Replace text in all files replaceall() { find . -type f -exec sed -i "s/$1/$2/g" {} +; } # Search command history alias h='history | grep' # Search processes psg() { ps aux | grep $1 | grep -v grep; }
Development Shortcuts
# Start simple HTTP server alias serve='python3 -m http.server 8000' # Generate random password genpass() { openssl rand -base64 ${1:-12}; } # JSON pretty print alias json='python3 -m json.tool' # Base64 encode/decode alias b64encode='base64' alias b64decode='base64 -d' # URL encode urlencode() { python3 -c "import urllib.parse; print(urllib.parse.quote('$1'))"; } # Check if website is up isup() { curl -Is $1 | head -1; } # Show certificate info certinfo() { openssl s_client -connect $1:443 </dev/null 2>/dev/null | openssl x509 -noout -dates; } # Quick note taking note() { echo "$1" >> ~/notes.txt; }
Pro Tips for Maximum Efficiency
1. Keep aliases organized
# Create ~/.bash_aliases for better organization touch ~/.bash_aliases # Add this to your ~/.bashrc if [ -f ~/.bash_aliases ]; then source ~/.bash_aliases fi
2. Create project-specific shortcuts: Tôi đã học điều này khi làm việc trên một dự án React, nơi tôi đã gõ cùng một lệnh npm 50 lần mỗi ngày.
# In your project folder, create .bash_project alias start='npm start' alias test='npm test' alias build='npm run build' alias deploy='npm run build && aws s3 sync build/ s3://my-bucket'
3. Use functions for complex workflows:
# Complete deployment function deploy() { echo "Starting deployment..." git add . && git commit -m "Deploy: $(date)" && git push origin main && kubectl apply -f k8s/ && echo "✅ Deployed successfully at $(date)" }
Bonus: One-Liners That Will Blow Your Mind
# Monitor file changes watch -n 1 'ls -la' # Show biggest directories du -h --max-depth=1 | sort -hr # Find broken symlinks find . -type l ! -exec test -e {} \; -print # Get weather curl wttr.in/YourCity # Generate QR code echo "Your text" | curl -F-=\<- qrenco.de # Share files instantly python3 -m http.server 8000 # Backup with timestamp cp file.txt "file-$(date +%Y%m%d_%H%M%S).txt" # Find largest files in current directory find . -type f -printf '%s %p\n' | sort -nr | head -10 # Monitor bandwidth usage iftop -i eth0 # Convert video to GIF ffmpeg -i input.mp4 -vf "fps=10,scale=320:-1" output.gif
Lời Cảnh Báo 🚨
Trước khi bạn go alias-crazy:
- Test aliases in a safe environment first
- Some commands can be destructive (especially Docker cleanup ones)
- Always backup important data before using cleanup commands
- The
rm
anddocker system prune
commands can’t be undone
Your Next Steps
Các bước thiết lập. Nhiều khi đã đưa hàng cho ae rồi nhưng ae vẫn còn chưa biết thiết lập là hơi dở rồi.
Step 1: Find Your Shell Config File
# Check which shell you're using echo $SHELL # For bash users nano or vi ~/.bashrc # For zsh users (Mac default) nano or vi ~/.zshrc
Step 2: Add Your Favorite Aliases
# Add these to the end of your ~/.bashrc or ~/.zshrc # Git shortcuts alias gs='git status -s' alias gac='git add . && git commit -m' alias gp='git push origin $(git branch --show-current)' # Docker shortcuts alias dstop='docker stop $(docker ps -q)' alias dclean='docker system prune -af' # Kubernetes shortcuts alias k='kubectl' alias kgp='kubectl get pods -o wide'
Step 3: Reload Your Shell
# Apply changes immediately source ~/.bashrc # OR source ~/.zshrc
Step 4: Test Your New Powers
Kinh nghiệm sử dụng
Câu Lệnh DevOps và Bash Aliases dùng sau 1 tháng là bạn thấy rõ sự khác biệt nhé. Tuy nhiên có một số lưu ý mà tôi đã gặp phải để bạn tránh nha.
- Mistake #1: cố gắng ghi nhớ tất cả 50 alias một lần. Không ăn được đâu. Nhớ 5 cái cần nhất trước, hay dùng cái nào thì nhớ. Dần dẫn sẽ tự động tăng thêm.
- Mistake #2: Tôi đã chạy
dclean
(docker system prune) mà không suy nghĩ và mất toàn bộ cơ sở dữ liệu phát triển của mình. Phải xây dựng lại mọi thứ từ đầu. Phải hiểu câu lệnh thì mới chạy nha. - Mistake #3: Tôi đã tạo alias với những cái tên gây nhầm lẫn như
dkrclnall
vàk8sgetpods
. Tôi không thể nhớ chúng làm gì. Tốt nhất là tạo tên alias theo cách riêng của bản thân và ngắn gọn.