macOS 早已經把預設的 shell 改為 zshell,提起 zshell 的配置,一般都會提到 ohmyzsh,但我覺得有點龐大,這下面是我自己的.zshrc 檔案,一個檔案走天下。

刪除了一些比較私人的 alias,參考了 oh-my-zsh 和網路上其他網友的一些設定,供參考。

# ================================================================
#    _____         _      _            _____
#   |_   _|       | |    ( )          /  __ \  https://tnl.casa
#     | |   _ __  | |    |/  ___      | /  \/  __ _  ___   __ _
#     | |  | '_ \ | |       / __|     | |     / _` |/ __| / _` |
#     | |  | | | || |____   \__ \     | \__/\| (_| |\__ \| (_| |
#     \_/  |_| |_|\_____/   |___/      \____/ \__,_||___/ \__,_|
# ================================================================

# Z Shell Manual Official Site
# https://zsh.sourceforge.io/Doc/Release/index.html


# ==================================Auto Completion
# The zsh/complist module offers three extensions to completion listings:
# the ability to highlight matches in such a list,
# the ability to scroll through long lists
# and a different style of menu completion.
zmodload -i zsh/complist

autoload -U compinit
compinit
# 貌似只有先啟用autoload compinit, 後面的compdef才能生效。
#
# Auto complete
# use setopt to show all setopt
unsetopt menu_complete   # do not autoselect the first completion entry
unsetopt flowcontrol
setopt auto_menu         # show completion menu on successive tab press
setopt complete_in_word
setopt always_to_end
# setopt AUTO_LIST
# bindkey -M menuselect '^o' accept-and-infer-next-history
zstyle ':completion:*:*:*:*:*' menu select

# Complete . and .. special directories
zstyle ':completion:*' special-dirs true

# show colors when use tab
zstyle ':completion:*' list-colors ''
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01'

zstyle ':completion:*:*:*:*:processes' command "ps -u $USERNAME -o pid,user,comm -w -w"

# disable named-directories autocompletion
zstyle ':completion:*:cd:*' tag-order local-directories directory-stack path-directories

# Use caching so that commands like apt and dpkg complete are useable
# zstyle ':completion:*' use-cache yes
# ZSH_CACHE_DIR=${HOME}/.cache
# zstyle ':completion:*' cache-path $ZSH_CACHE_DIR

# Don't complete uninteresting users
zstyle ':completion:*:*:*:users' ignored-patterns \
        adm amanda apache at avahi avahi-autoipd beaglidx bin cacti canna \
        clamav daemon dbus distcache dnsmasq dovecot fax ftp games gdm \
        gkrellmd gopher hacluster haldaemon halt hsqldb ident junkbust kdm \
        ldap lp mail mailman mailnull man messagebus  mldonkey mysql nagios \
        named netdump news nfsnobody nobody nscd ntp nut nx obsrun openvpn \
        operator pcap polkitd postfix postgres privoxy pulse pvm quagga radvd \
        rpc rpcuser rpm rtkit scard shutdown squid sshd statd svn sync tftp \
        usbmux uucp vcsa wwwrun xfs '_*'
# ... unless we really want to.
zstyle '*' single-ignored show

#補全型別提示分組
zstyle ':completion:*:matches' group 'yes'
zstyle ':completion:*' group-name ''
zstyle ':completion:*:options' description 'yes'
zstyle ':completion:*:options' auto-description '%d'
zstyle ':completion:*:descriptions' format $'\e[01;33m -- %d --\e[0m'
zstyle ':completion:*:messages' format $'\e[01;35m -- %d --\e[0m'
zstyle ':completion:*:warnings' format $'\e[01;31m -- No Matches Found --\e[0m'
zstyle ':completion:*:corrections' format $'\e[01;32m -- %d (errors: %e) --\e[0m'

# # cd ~ 補全順序
# zstyle ':completion:*:-tilde-:*' group-order 'named-directories' 'path-directories' 'users' 'expand'
# ==================================Auto Completion END

# 環境變數,裝doom和homebrew的才會用到。已註釋掉。
# export PATH=~/.emacs.d/bin:$PATH
# export PATH="/usr/local/sbin:$PATH"

###################################### Directories Relatives===form ohmyzsh
# Changing/making/removing directory
setopt auto_pushd
setopt pushd_ignore_dups
setopt pushdminus

alias -g ...='../..'
alias -g ....='../../..'
alias -g .....='../../../..'
alias -g ......='../../../../..'

alias -- -='cd -'
alias ..='cd ..'
alias 1='cd -1'
alias 2='cd -2'
alias 3='cd -3'
alias 4='cd -4'
alias 5='cd -5'
alias 6='cd -6'
alias 7='cd -7'
alias 8='cd -8'
alias 9='cd -9'

alias md='mkdir -p'
alias rd=rmdir

function d () {
  if [[ -n $1 ]]; then
    dirs "$@"
  else
    dirs -v | head -n 10
  fi
}
compdef _dirs d
# cd 只列出目錄,取消註釋下面一行可列出所有目錄和檔案
# compdef _path_files cd

# List directory contents
alias la='ls -lahF'
alias lf='ls -lhF'
alias ll='ls -lAFh'

######################################End Directories Relatives===most from ohmyzsh
# ======================================History Settings==========================
## History wrapper
function omz_history {
  local clear list
  zparseopts -E c=clear l=list

  if [[ -n "$clear" ]]; then
    # if -c provided, clobber the history file
    echo -n >| "$HISTFILE"
    fc -p "$HISTFILE"
    echo >&2 History file deleted.
  elif [[ -n "$list" ]]; then
    # if -l provided, run as if calling `fc' directly
    builtin fc "$@"
  else
    # unless a number is provided, show all history events (starting from 1)
    [[ ${@[-1]-} = *[0-9]* ]] && builtin fc -l "$@" || builtin fc -l "$@" 1
  fi
}

# Timestamp format
case ${HIST_STAMPS-} in
  "mm/dd/yyyy") alias history='omz_history -f' ;;
  "dd.mm.yyyy") alias history='omz_history -E' ;;
  "yyyy-mm-dd") alias history='omz_history -i' ;;
  "") alias history='omz_history' ;;
  *) alias history="omz_history -t '$HIST_STAMPS'" ;;
esac

## History file configuration
[ -z "$HISTFILE" ] && HISTFILE="$HOME/.zsh_history"
[ "$HISTSIZE" -lt 50000 ] && HISTSIZE=50000
[ "$SAVEHIST" -lt 10000 ] && SAVEHIST=10000

## History command configuration
setopt extended_history       # record timestamp of command in HISTFILE
setopt hist_expire_dups_first # delete duplicates first when HISTFILE size exceeds HISTSIZE
setopt hist_ignore_dups       # ignore duplicated commands history list
setopt hist_ignore_space      # ignore commands that start with space
setopt hist_verify            # show command with history expansion to user before running it
setopt share_history          # share command history data


alias h='omz_history -i'


# ========================================History END
#
#
############################################################## ALIASES SETTINGS
# 根據自己的代理情況設定,不同的程式可能要求不同的環境變數,下面這個適合curl。
alias proxy='export all_proxy=socks5://192.168.3.1:1087'
alias proxyh='export all_proxy=socks5h://192.168.3.1:1087'
alias unproxy='unset all_proxy'
# 自己寫的指令碼檢視當前的ip地址。
# alias showip='curl ipinfo.io'
function showip () {
    local nflag
    local defip=127
    local sa='cip.cc'
    local sb='ipinfo.io'
    local sc='ifconfig.me'
    local sd='https://ipapi.co/json'
    # local se='https://ipapi.co/json'
    # local sf='https://ipapi.co/json'
    # local sg='https://ipapi.co/json'

    if [ $# = 0 ]; then
        printf "\n"
        printf '0\tor q for Quit. You can sum for multi selection\n'
        printf '1\t%s\n' $sa
        printf '2\t%s\n' $sb
        printf '4\t%s\n' $sc
        printf '8\t%s\n' $sd
        # printf '16\t%s\n' $se
        # printf '32\t%s\n' $sf
        # printf '64\t%s\n' $sg

        printf 'Please select test site: enter for all:'
        read -r nflag
        if [ -z ${nflag} ]; then
            nflag=${defip}
            # echo 'NULL'
        fi
    else
        nflag="$1"
    fi

    if grep -q '^[[:digit:]]*$' <<< "${nflag}"; then
        if [[ $((nflag & 1)) != 0 ]]; then
            printf 'curl %s...\n' $sa
            curl "${sa}"
            printf '\n'
        fi
        if [[ $((nflag & 2)) != 0 ]]; then
            printf 'curl %s...\n' $sb
            curl "${sb}"
            printf '\n'
        fi
        if [[ $((nflag & 4)) != 0 ]]; then
            printf 'curl %s...\n' $sc
            curl "${sc}"
            printf '\n'
        fi
        if [[ $((nflag & 8)) != 0 ]]; then
            printf 'curl %s...\n' $sd
            curl "${sd}"
            printf '\n'
        fi
        # if [[ $((nflag & 16)) != 0 ]]; then
        #     printf 'curl %s...\n' $se
        #     curl "${se}"
        #     printf '\n'
        # fi
        # if [[ $((nflag & 32)) != 0 ]]; then
        #     printf 'curl %s...\n' $sf
        #     curl "${sf}"
        #     printf '\n'
        # fi
        # if [[ $((nflag & 64)) != 0 ]]; then
        #     printf 'curl %s...\n' $sg
        #     curl "${sg}"
        #     printf '\n'
        # fi
    elif [[ ${nflag} = "q" ]]; then
        return
    fi
}
# Use Crtl-z to put a process background
# use j to show background process
# use fg [%n] to make it foreground
alias j='jobs -l'

#terry added
alias gb2u8='iconv -c -f GBK -t UTF-8'

alias ff='find . -type f -name'

alias q='exit'
alias rm='rm -i'
alias del='rm -r'
alias mv='mv -i'
alias cp='cp -i'
alias dh='df -hat'
alias dus='du -cshx *'
alias ds='du -cshx * -print 2>/dev/null'
alias v='vi'
alias g='git'
# alias hdemo='hugo server --themesDir ../..'
# alias hs='hugo server -D --bind "0.0.0.0"'
alias zrc='vi ~/.zshrc'
alias zrf='source ~/.zshrc'
# alias ss='ssh [email protected]'
# alias sswww='ssh [email protected]'
# alias ssdl='ssh [email protected]'
alias s='sudo -s'
alias h20='head -n 20'
# alias minstall  'make install clean'
alias sharecurdir='python3 -m http.server'
alias -s gz='tar -xzvf'
alias -s tgz='tar -xzvf'
alias -s zip='unzip'
alias -s bz2='tar -xjvf'
alias -s rar='unrar x'

# Command line head / tail shortcuts
# -g 為global選項,慎用。
# Lastly, there are `global aliases'.
# If aliases can get you into a lot of trouble,
# global aliases can get you into a lot of a lot of trouble.
# They are defined with the option -g
# and are expanded not just in command position,
# but anywhere on the command line.

alias -g H='| head'
alias -g T='| tail'
alias -g G='| grep'
alias -g L="| less"
alias -g M="| most"
alias -g LL="2>&1 | less"
alias -g CA="2>&1 | cat -A"
alias -g NE="2> /dev/null"
alias -g NUL="> /dev/null 2>&1"
alias -g P="2>&1| pygmentize -l pytb"
alias -g nLines='| wc -l'
############################################################## ALIASES SETTINGS END

##### =======================================KEY BINDINGS
# bindkey "\e[A" history-beginning-search-backward
# bindkey "\e[B" history-beginning-search-forward
# autoload -U up-line-or-beginning-search
# zle -N up-line-or-beginning-search
# autoload -U down-line-or-beginning-search
# zle -N down-line-or-beginning-search
# bindkey "\e[A" up-line-or-beginning-search
# bindkey "\e[B" down-line-or-beginning-search
bindkey "\e[A" up-line-or-search
bindkey "\e[B" down-line-or-search
# bindkey '^r' history-incremental-search-backward
# bindkey "\e[H" # HOME up-line-or-search
# bindkey "\e[F" # END up-line-or-search
# bindkey "\e[A" up-line-or-search
# bindkey "\e[A" up-line-or-search


# ##在命令前插入 sudo
sudo-command-line() {
    [[ -z $BUFFER ]] && zle up-history
    [[ $BUFFER != sudo\ * ]] && BUFFER="sudo $BUFFER"
    zle end-of-line
}
zle -N sudo-command-line
bindkey "\e\e" sudo-command-line


##### END KEY BINDINGS




# ========================================PROMPT===========================
PROMPT='%F{cyan}%B%~%b %n@%m %D %*
%(?.%B%F{green}√.%F{red}?%?)%f%b %B%F{240}%1~%f%b %B%(!.%F{red}#.%F{green}>)%b '
PROMPT=$'${(r:$COLUMNS::=:)}'$PROMPT

# ========================================PROMPT END===========================

#=========================================yufagaoliang
setopt extended_glob
TOKENS_FOLLOWED_BY_COMMANDS=('|' '||' ';' '&' '&&' 'sudo' 'do' 'time' 'strace' 'man')

recolor-cmd() {
    region_highlight=()
    colorize=true
    start_pos=0
    for arg in ${(z)BUFFER}; do
        ((start_pos+=${#BUFFER[$start_pos+1,-1]}\
            -${#${BUFFER[$start_pos+1,-1]## #}}))
        ((end_pos=$start_pos+${#arg}))
        if $colorize; then
            colorize=false
            res=$(LC_ALL=C builtin type $arg 2>/dev/null)
            case $res in
                *'reserved word'*)   style="fg=magenta,bold";;
                *'alias for'*)       style="fg=cyan,bold";;
                *'shell builtin'*)   style="fg=yellow,bold";;
                *'shell function'*)  style='fg=green,bold';;
                *"$arg is"*)
                    [[ $arg = 'sudo' ]] && style="fg=red,bold"\
                                  || style="fg=blue,bold";;
                *)                   style='none,bold';;
            esac
            region_highlight+=("$start_pos $end_pos $style")
        fi
        [[ ${${TOKENS_FOLLOWED_BY_COMMANDS[(r)${arg//|/\|}]}:+yes} = 'yes' ]]\
            && colorize=true
        start_pos=$end_pos
    done
}

check-cmd-self-insert() { zle .self-insert && recolor-cmd }
check-cmd-backward-delete-char() { zle .backward-delete-char && recolor-cmd }

zle -N self-insert check-cmd-self-insert
zle -N backward-delete-char check-cmd-backward-delete-char

export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
# export LSCOLORS="Gxfxcxdxbxegedabagacad"
#=========================================yufagaoliang end

# ==========================================vterm相關設定,我是配合emacs vterm使用,沒有安裝的可以忽略。
vterm_printf(){
    if [ -n "$TMUX" ]; then
        # Tell tmux to pass the escape sequences through
        # (Source: http://permalink.gmane.org/gmane.comp.terminal-emulators.tmux.user/1324)
        printf "\ePtmux;\e\e]%s\007\e\\" "$1"
    elif [ "${TERM%%-*}" = "screen" ]; then
        # GNU screen (screen, screen-256color, screen-256color-bce)
        printf "\eP\e]%s\007\e\\" "$1"
    else
        printf "\e]%s\e\\" "$1"
    fi
}

vterm_cmd() {
    local vterm_elisp
    vterm_elisp=""
    while [ $# -gt 0 ]; do
        vterm_elisp="$vterm_elisp""$(printf '"%s" ' "$(printf "%s" "$1" | sed -e 's|\\|\\\\|g' -e 's|"|\\"|g')")"
        shift
    done
    vterm_printf "51;E$vterm_elisp"
}
if [[ "$INSIDE_EMACS" = 'vterm' ]]; then
    o() {
        vterm_cmd find-file "$(realpath "${@:-.}")"
    }
    alias clear='vterm_printf "51;Evterm-clear-scrollback";tput clear'
fi
vterm_prompt_end() {
    vterm_printf "51;A$(whoami)@$(hostname):$(pwd)";
}
setopt PROMPT_SUBST
PROMPT=$PROMPT'%{$(vterm_prompt_end)%}'
# ==========================================vterm相關設定 END

老張說:

為了配置自己的 .zshrc 檔案,網上查詢了很多資料,中文資料不是特別多,而且翻來覆去就那麼兩三篇文章,內容感覺有點老舊。於是有看了下 oh-my-zsh 的部分程式碼,借鑑了很多。完成了這個設定。自我感覺還是非常好用的。

而且所有的檔案都在 .zshrc 之中,算是比較輕量級,拿來就能用。

支援我們

如果您喜欢这篇文章,您可以分享给您的朋友,分享到您的社交账号比如:

或者 点击这个链接 观看广告支持我【广告内容与我们无关,请不要轻易相信并打开弹出的广告】。
若您经济宽裕,更欢迎通过下面的方式小额赞助以支持我们的创作。