Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình Bash

Làm chủ .bashrc: Tạo Aliases, Functions & Tăng Năng Suất Linux

Tùy chỉnh file .bashrc có thể cải thiện đáng kể quy trình làm việc và tăng năng suất.

File .bashrc là file tiêu chuẩn nằm trong thư mục home Linux của bạn. Trong bài này tôi sẽ chỉ các tùy chọn .bashrc hữu ích, aliases, functions, và hơn thế nữa.

Lợi ích chính của cấu hình file .bashrc:

  • Thêm aliases cho phép gõ lệnh nhanh hơn, tiết kiệm thời gian.
  • Thêm functions cho phép lưu và chạy lại code phức tạp.
  • Hiển thị thông tin hệ thống hữu ích.
  • Tùy chỉnh Bash prompt.

Cách bắt đầu chỉnh sửa .bashrc

Cách chỉnh sửa file .bashrc bằng trình soạn thảo văn bản:

$ vim ~/.bashrc

Bạn có thể thêm định dạng ngày giờ cho bash history.

HISTTIMEFORMAT="%F %T "
# Output $ history
1017 20210228 10:51:28 uptime
1019 20210228 10:52:42 free -m
1020 20210228 10:52:49 tree --dirsfirst -F
1018 20210228 10:51:38 xrandr | awk '/\*/{print $1}'

Thêm dòng này để bỏ qua lệnh trùng lặp trong history.

HISTCONTROL=ignoredups

Để đặt số dòng trong history đang hoạt động và số dòng lưu trong Bash history, thêm hai dòng này.

HISTSIZE=2000
HISTFILESIZE=2000

Bạn có thể đặt history để append (thêm vào) thay vì ghi đè Bash history. shopt nghĩa là "shell options".

shopt -s histappend

Để xem tất cả shell options mặc định, chạy shopt -p.

# Output $ shopt -p
shopt -u autocd
shopt -u assoc_expand_once
shopt -u cdable_vars
shopt -u cdspell
shopt -u checkhash
shopt -u checkjobs
shopt -s checkwinsize
[...]

Tạo biến để thêm màu cho Bash prompt như sau:

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

Đây là cho người yêu Vim. Cho phép dùng lệnh vim trên dòng lệnh. Đây luôn là dòng đầu tiên tôi thêm vào .bashrc.

set -o vi

Cách tạo Aliases trong .bashrc

Bạn có thể dùng aliases cho các lệnh chạy thường xuyên. Tạo aliases cho phép gõ nhanh hơn, tiết kiệm thời gian và tăng năng suất.

Cú pháp tạo alias là alias <my_alias>='longer command'. Để biết lệnh nào nên tạo alias, chạy lệnh này xem top 10 lệnh bạn chạy nhiều nhất:

$ history | awk '{cmd[$2]++} END {for(elem in cmd) {print cmd[elem] " " elem}}' | sort -n -r | head -10
# Output
171 git
108 cd
62 vim
51 python3
38 history
32 exit
30 clear
28 tmux
28 tree
27 ls

Vì tôi dùng Git nhiều, đó là lệnh tuyệt vời để tạo alias.

# Xem Git status.
alias gs='git status'
# Thêm file vào Git.
alias ga='git add'
# Thêm tất cả file vào Git.
alias gaa='git add --all'
# Commit thay đổi code.
alias gc='git commit'
# Xem Git log.
alias gl='git log --oneline'
# Tạo branch Git mới và chuyển sang branch đó cùng lúc.
alias gb='git checkout -b'
# Xem sự khác biệt.
alias gd='git diff'

Dưới đây là một số alias hữu ích khác:

# Di chuyển đến thư mục cha.
alias ..='cd ..;pwd'
# Di chuyển lên 2 thư mục cha.
alias ...='cd ../..;pwd'
# Di chuyển lên 3 thư mục cha.
alias ....='cd ../../..;pwd'
# Nhấn c để xóa màn hình terminal.
alias c='clear'
# Nhấn h để xem bash history.
alias h='history'
# Hiển thị cấu trúc thư mục tốt hơn.
alias tree='tree --dirsfirst -F'
# Tạo thư mục và tất cả thư mục cha với verbosity.
alias mkdir='mkdir -p -v'
# Xem lịch bằng cách gõ 3 chữ cái đầu của tháng.
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'
# Output $ mar
March 2021
Su Mo Tu We Th Fr Sa
1  2  3  4  5  6  7
8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Cách dùng Functions trong .bashrc

Functions tuyệt vời cho code phức tạp khi alias không đủ.

Cú pháp function cơ bản:

function funct_name() {
  # code;
}

Cách tìm file lớn nhất trong thư mục:

function find_largest_files() {
  du -h -x -s -- * | sort -r -h | head -20;
}
# Output
Downloads $ find_largest_files
709M systemrescue-8.00-amd64.iso
337M debian-10.8.0-amd64-netinst.iso
9.1M weather-icons-master.zip
6.3M Hack-font.zip
3.9M city.list.json.gz
2.8M dvdrental.tar
708K IMG_2600.JPG
100K sql_cheat_sheet_pgsql.pdf
4.0K repeating-a-string.txt
4.0K heart.svg
4.0K Fedora-Workstation-33-1.2-x86_64-CHECKSUM
[...]

Bạn cũng có thể thêm màu cho Bash prompt và hiển thị branch Git hiện tại như sau:

# Hiển thị branch Git hiện tại trong Bash prompt.
function git_branch() {
  if [ -d .git ] ; then
    printf "%s" "($(git branch 2> /dev/null | awk '/\*/{print $2}'))";
  fi
}
# Thiết lập prompt.
function bash_prompt(){
  PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}
}
bash_prompt

Grep (tìm kiếm) trong history các lệnh đã chạy trước:

function hg() {
  history | grep "$1";
}
# Output
$ hg vim
305 2021-03-02 16:47:33 vim .bashrc
307 2021-03-02 17:17:09 vim .tmux.conf

Cách bắt đầu dự án mới với 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
}
# Output
$ git_init my_project
/home/brandon/my_project
Initialized empty Git repository in /home/brandon/my_project/.git/

Bạn cũng có thể lấy báo cáo thời tiết trên dòng lệnh. Yêu cầu gói curl, jq, và API key từ Openweathermap. Đọc tài liệu API Openweathermap để cấu hình URL đúng để lấy thời tiết tại vị trí của bạn.

Cài curl và jq bằng lệnh:

$ sudo apt install curl jq
# OR
$ sudo dnf install curl jq
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')
  # Check for the 200 response indicating a successful API query.
  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
}
# Output
$ weather_report
Location: "New York" "US"
Forecast: "clear sky"
Temperature: 58.0°F
Temp Min: 56.0°F
Temp Max: 60.8°F

Cách in thông tin hệ thống trong .bashrc

Bạn có thể hiển thị thông tin hệ thống hữu ích khi mở terminal như sau:

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"

Output:

Source file .bashrc để thay đổi có hiệu lực:

$ source ~/.bashrc

Dưới đây là tất cả cài đặt .bashrc tùy chỉnh cùng nhau. Trên hệ thống mới, tôi dán tùy chỉnh dưới code mặc định trong file .bashrc.

######################################################################
# # # ██████╗ █████╗ ███████╗██╗ ██╗██████╗ ██████╗
# ██╔══██╗██╔══██╗██╔════╝██║ ██║██╔══██╗██╔════╝
# ██████╔╝██║ ██║███████║███████║██████╔╝██║
# ██╔══██╗██╔══██║╚════██║██╔══██║██╔══██╗██║
# ██████╔╝██║ ██║███████║██║ ██║██║ ██║╚██████╗
# ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═════╝
# #
######################################################################
set -o vi
HISTTIMEFORMAT="%F %T "
HISTCONTROL=ignoredups
HISTSIZE=2000
HISTFILESIZE=2000
shopt -s histappend
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
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'
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'
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'
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
}
# Set the prompt.
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
}
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"

Kết luận

Trong bài này bạn học cách cấu hình các tùy chọn .bashrc, aliases, functions, và hơn thế nữa để cải thiện đáng kể quy trình làm việc và tăng năng suất.

Theo dõi tôi trên Github | Dev.to.