Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

เชี่ยวชาญ .bashrc: สร้าง Aliases, Functions เพิ่มประสิทธิภาพ Linux

การปรับแต่งไฟล์ .bashrc สามารถปรับปรุง Workflow และเพิ่มประสิทธิภาพการทำงานได้อย่างมาก

.bashrc เป็นไฟล์มาตรฐานที่อยู่ใน Home Directory ของ Linux ในบทความนี้จะแนะนำตัวเลือก Aliases, Functions และการตั้งค่าต่างๆ ที่มีประโยชน์

ประโยชน์หลักของการตั้งค่า .bashrc

  • Aliases: พิมพ์คำสั่งสั้นแทนคำสั่งยาว — ประหยัดเวลา
  • Functions: บันทึกและรันโค้ดซับซ้อนซ้ำได้
  • System Info: แสดงข้อมูลระบบที่มีประโยชน์ตอนเปิด Terminal
  • Prompt: ปรับแต่ง Bash Prompt ให้อ่านง่ายและมีข้อมูลครบ

เริ่มต้นแก้ไข .bashrc

vim ~/.bashrc

ตั้งค่า History

# แสดงวันที่เวลาใน History
HISTTIMEFORMAT="%F %T "

# ไม่บันทึกคำสั่งซ้ำ
HISTCONTROL=ignoredups

# จำนวนบรรทัดใน Active History และไฟล์ History
HISTSIZE=2000
HISTFILESIZE=2000

# Append History แทน Overwrite
shopt -s histappend

ดู Shell Options ทั้งหมด: shopt -p

สร้างตัวแปรสีสำหรับ Prompt

blk='\[\033[01;30m\]'  # Black
red='\[\033[01;31m\]'  # Red
grn='\[\033[01;32m\]'  # Green
ylw='\[\033[01;33m\]'  # Yellow
blu='\[\033[01;34m\]'  # Blue
pur='\[\033[01;35m\]'  # Purple
cyn='\[\033[01;36m\]'  # Cyan
wht='\[\033[01;37m\]'  # White
clr='\[\033[00m\]'     # Reset

โหมด Vim บนบรรทัดคำสั่ง

set -o vi

สร้าง Aliases ใน .bashrc

หาคำสั่งที่ใช้บ่อยที่สุด:

history | awk '{cmd[$2]++} END {for(elem in cmd) {print cmd[elem] " " elem}}' | sort -n -r | head -10

Aliases สำหรับ Git (ตัวอย่าง)

alias gs='git status'
alias ga='git add'
alias gaa='git add --all'
alias gc='git commit'
alias gl='git log --oneline'
alias gb='git checkout -b'
alias gd='git diff'

Aliases นำทางไดเรกทอรี

alias ..='cd ..;pwd'
alias ...='cd ../..;pwd'
alias ....='cd ../../..;pwd'

Aliases ทั่วไป

alias c='clear'
alias h='history'
alias tree='tree --dirsfirst -F'
alias mkdir='mkdir -p -v'

Aliases ปฏิทิน (Calendar)

alias jan='cal -m 01'
alias feb='cal -m 02'
# ... จนถึง dec='cal -m 12'

ใช้ Functions ใน .bashrc

Functions เหมาะสำหรับโค้ดซับซ้อนที่ Alias ทำไม่ได้

Syntax พื้นฐาน

function funct_name() {
  # code;
}

หาไฟล์ขนาดใหญ่ที่สุดในไดเรกทอรี

function find_largest_files() {
  du -h -x -s -- * | sort -r -h | head -20
}

แสดง Git Branch ใน Prompt

function git_branch() {
  if [ -d .git ]; then
    printf "%s" "($(git branch 2>/dev/null | awk '/\*/{print $2}'))"
  fi
}

function bash_prompt(){
  PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}
}
bash_prompt

ค้นหาใน History (grep history)

function hg() {
  history | grep "$1"
}

เริ่มโปรเจกต์ใหม่พร้อม Git

function git_init() {
  if [ -z "$1" ]; then
    printf "%s\n" "Please provide a directory name."
  else
    mkdir "$1"
    builtin cd "$1"
    pwd
    git init
    touch readme.md .gitignore LICENSE
    echo "# $(basename $PWD)" >> readme.md
  fi
}

ดูสภาพอากาศบน Terminal (ต้องมี curl, jq, API Key)

function weather_report() {
  local response=$(curl --silent 'https://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial&appid=')
  local status=$(echo $response | jq -r '.cod')
  case $status in
    200)
      printf "Location: %s %s\n" "$(echo $response | jq '.name')" "$(echo $response | jq '.sys.country')"
      printf "Forecast: %s\n" "$(echo $response | jq '.weather[].description')"
      printf "Temperature: %.1f°F\n" "$(echo $response | jq '.main.temp')"
      printf "Temp Min: %.1f°F\n" "$(echo $response | jq '.main.temp_min')"
      printf "Temp Max: %.1f°F\n" "$(echo $response | jq '.main.temp_max')"
      ;;
    401) echo "401 error" ;;
    *) echo "error" ;;
  esac
}

แสดงข้อมูลระบบตอนเปิด Terminal

clear
printf "\n"
printf " %s\n" "IP ADDR: $(curl ifconfig.me)"
printf " %s\n" "USER: $(echo $USER)"
printf " %s\n" "DATE: $(date)"
printf " %s\n" "UPTIME: $(uptime -p)"
printf " %s\n" "HOSTNAME: $(hostname -f)"
printf " %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)"
printf " %s\n" "KERNEL: $(uname -rms)"
printf " %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)"
printf " %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1\" \"}')"
printf " %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3\"/\"$2}')"
printf "\n"

นำการเปลี่ยนแปลงเข้าใช้

source ~/.bashrc

ไฟล์ .bashrc เต็ม (รวมทุกอย่าง)

######################################################################
# Custom .bashrc
######################################################################
set -o vi
HISTTIMEFORMAT="%F %T "
HISTCONTROL=ignoredups
HISTSIZE=2000
HISTFILESIZE=2000
shopt -s histappend

# Colors
blk='\[\033[01;30m\]'; red='\[\033[01;31m\]'; grn='\[\033[01;32m\]'
ylw='\[\033[01;33m\]'; blu='\[\033[01;34m\]'; pur='\[\033[01;35m\]'
cyn='\[\033[01;36m\]'; wht='\[\033[01;37m\]'; clr='\[\033[00m\]'

# Git Aliases
alias gs='git status'; alias ga='git add'; alias gaa='git add --all'
alias gc='git commit'; alias gl='git log --oneline'
alias gb='git checkout -b'; alias gd='git diff'

# Navigation
alias ..='cd ..;pwd'; alias ...='cd ../..;pwd'; alias ....='cd ../../..;pwd'
alias c='clear'; alias h='history'
alias tree='tree --dirsfirst -F'; alias mkdir='mkdir -p -v'

# Calendar
alias jan='cal -m 01'; alias feb='cal -m 02'; alias mar='cal -m 03'
alias apr='cal -m 04'; alias may='cal -m 05'; alias jun='cal -m 06'
alias jul='cal -m 07'; alias aug='cal -m 08'; alias sep='cal -m 09'
alias oct='cal -m 10'; alias nov='cal -m 11'; alias dec='cal -m 12'

# Functions
function hg() { history | grep "$1"; }
function find_largest_files() { du -h -x -s -- * | sort -r -h | head -20; }
function git_branch() { if [ -d .git ]; then printf "%s" "($(git branch 2>/dev/null | awk '/\*/{print $2}'))"; fi }
function bash_prompt(){ PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}; }
bash_prompt
function git_init() { if [ -z "$1" ]; then printf "%s\n" "Please provide a directory name."; else mkdir "$1"; builtin cd "$1"; pwd; git init; touch readme.md .gitignore LICENSE; echo "# $(basename $PWD)" >> readme.md; fi }
function weather_report() { local response=$(curl --silent 'https://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial&appid='); local status=$(echo $response | jq -r '.cod'); case $status in 200) printf "Location: %s %s\n" "$(echo $response | jq '.name')" "$(echo $response | jq '.sys.country')"; printf "Forecast: %s\n" "$(echo $response | jq '.weather[].description')"; printf "Temperature: %.1f°F\n" "$(echo $response | jq '.main.temp')"; printf "Temp Min: %.1f°F\n" "$(echo $response | jq '.main.temp_min')"; printf "Temp Max: %.1f°F\n" "$(echo $response | jq '.main.temp_max')"; ;; 401) echo "401 error";; *) echo "error";; esac; }

# System Info on startup
clear; printf "\n"
printf " %s\n" "IP ADDR: $(curl ifconfig.me)"
printf " %s\n" "USER: $(echo $USER)"
printf " %s\n" "DATE: $(date)"
printf " %s\n" "UPTIME: $(uptime -p)"
printf " %s\n" "HOSTNAME: $(hostname -f)"
printf " %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)"
printf " %s\n" "KERNEL: $(uname -rms)"
printf " %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)"
printf " %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1\" \"}')"
printf " %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3\"/\"$2}')"
printf "\n"

สรุป

บทความนี้ครอบคลุมการตั้งค่า .bashrc ต่างๆ: Aliases, Functions, Prompt, System Info — ทั้งหมดช่วยเพิ่มประสิทธิภาพและลด Keystrokes ได้มาก ติดตามได้ที่ GitHub | Dev.to