Timetombs

泛义的工具是文明的基础,而确指的工具却是愚人的器物

66h / 117a
,更新于 2024-10-29T22:15:38Z+08:00 by   c73aa5b

[Linux] Bash Script

版权声明 - CC BY-NC-SA 4.0

1 Script File List

sh文件列表
# .zshrc(z shell run commands)

source $(dirname $0)/env.sh
source $(dirname $0)/function.sh
source $(dirname $0)/function-string.sh
source $(dirname $0)/function-directory.sh
source $(dirname $0)/function-git.sh
source $(dirname $0)/function-proc.sh
source $(dirname $0)/function-date.sh
source $(dirname $0)/git-prompt.sh
source $(dirname $0)/zsh-prompt.sh
source $(dirname $0)/vscode.sh
source $(dirname $0)/idea.sh
source $(dirname $0)/zsh-compdef.sh
source $(dirname $0)/alias.sh
# alias
alias ..='cd ..'
alias ...='cd ../..'
alias d='__directory_to'
alias c='__vscode_open'
alias i='__idea_open'
alias t='__timestamp_2_iso8601'

alias dr='docker run --rm --tty --interactive'
alias dre='dr --entrypoint'
alias drs='dre sh'
alias drb='dre bash'
alias dh='docker history --human --no-trunc'
alias dc='docker-compose'
alias dm='docker-machine'
alias mk='minikube'

alias h='history | grep'

alias md='mkdir -p'

alias bak='backup_file'

alias cls='clear'

alias grep='grep --color=auto'

alias untar='tar -z -x -v -f'

alias wget='wget --continue --show-progress'

alias sha='shasum --algorithm 1'
alias sha256='shasum --algorithm 256'

alias ping='ping -c 5'

alias ipe='curl http://ifconfig.me/ip'
alias ipl='ipconfig getifaddr en0'

alias hs='miniserve --color-scheme squirrel --qrcode'
alias hsu='hs --upload-files'

alias pfd='rinetd --conf-file /lnh/_code/blog/src/tool/rinetd/rinetd.conf'
alias pf='pfd --foreground'

alias env='env | sort'

alias penv='proc_env'

alias penv2='proc_env2'

# https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
alias path='echo "${PATH//:/\n}"'

# https://github.com/jeremyfa/yaml.js
# cnpm install -yamljs -g
alias yj='yaml2json --pretty --indentation 2'

alias jy='json2yaml --depth 64 --indentation 2'

alias shell='echo $SHELL'

alias shells='cat /etc/shells'

alias i18n='locale'

alias hu='hugo --config hugo.yml --buildDrafts --forceSyncStatic --panicOnWarning'

alias hus='hu --watch server'

alias mvn-wrapper='mvn --non-recursive --debug io.takari:maven:wrapper -Dmaven=3.8.1'

alias gradle-wrapper='gradle wrapper --distribution-type all --gradle-version 6.7'

alias mvn-help='./mvnw help:describe -Ddetail'

alias java-x='java -X'
alias java-xx='java -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+PrintFlagsFinal -version'
alias java8='export JAVA_HOME=$JAVA_8_HOME && java -version'
alias java11='export JAVA_HOME=$JAVA_11_HOME && java -version'
alias java17='export JAVA_HOME=$JAVA_17_HOME && java -version'
alias java21='export JAVA_HOME=$JAVA_21_HOME && java -version'

alias proxy='export ALL_PROXY=socks5://127.0.0.1:1080'
alias unproxy='unset ALL_PROXY'

alias redis-server='redis-server /lnh/_code/blog/src/redis/install/redis.conf'

alias ja='java -jar $JAVA_HOME/arthas-boot.jar --repo-mirror aliyun --use-http'

alias master='git co master'
alias main='git co main'
alias g='git'
alias gti='git'
alias gi='git'
# java -cp $JAVA_HOME/lib/sa-jdi.jar sun.jvm.hotspot.HSDB

alias k='kubectl'
alias kp='k get pods'
alias kpt='kp -o custom-columns-file=/lnh/_code/blog/src/k8s/kubectl/terminated-pod.txt --sort-by="{.status.containerStatuses[0].lastState.terminated.finishedAt}"'
MY_HOME=/lnh
APP_DIR=$MY_HOME/_app
CACHE_DIR=$MY_HOME/_cache
CONFIG_DIR=$MY_HOME/_config
DATA_DIR=$MY_HOME/_data

# add gnu
PATH=/usr/local/opt/coreutils/libexec/gnubin:$PATH

# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
export XDG_CACHE_HOME=$CACHE_DIR
export XDG_CONFIG_HOME=$CONFIG_DIR
export XDG_DATA_HOME=$DATA_DIR

# https://docs.microsoft.com/en-us/dotnet/core/tools/telemetry
# https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-tool-install
export DOTNET_CLI_TELEMETRY_OPTOUT=false
APP_DOTNET_DIR=$APP_DIR/_dotnet
DOTNET_TOOLS_DIR=$HOME/.dotnet/tools
export PATH=$PATH:$APP_DOTNET_DIR:$DOTNET_TOOLS_DIR

# https://adoptopenjdk.net/releases.html?variant=openjdk11&jvmVariant=hotspot
# APP_JAVA_DIR=$APP_DIR/_java
# APP_JAVA_BIN_DIR=$APP_JAVA_DIR/bin
# export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8
# export JAVA_HOME=$APP_JAVA_DIR
# export PATH=$PATH:$APP_JAVA_BIN_DIR

# https://gradle.org/releases/
APP_GRADLE_DIR=$APP_DIR/_gradle
APP_GRADLE_BIN_DIR=$APP_GRADLE_DIR/bin
CACHE_GRADLE_DIR=$CACHE_DIR/_gradle
export GRADLE_HOME=$APP_GRADLE_DIR
export GRADLE_USER_HOME=$CACHE_GRADLE_DIR
export PATH=$PATH:$APP_GRADLE_BIN_DIR

# https://maven.apache.org/
# http://maven.apache.org/configure.html
APP_MAVEN_DIR=$APP_DIR/_maven
APP_MAVEN_BIN_DIR=$APP_MAVEN_DIR/bin
CACHE_MAVEN_DIR=$CACHE_DIR/_maven
export MAVEN_HOME=$APP_MAVEN_DIR
export M2_HOME=$MAVEN_HOME
export MAVEN_USER_HOME=$MAVEN_HOME
export MAVEN_OPTS='-Xms256m -Xmx1024m'
export PATH=$PATH:$APP_MAVEN_BIN_DIR

# https://projects.spring.io/spring-boot/
# APP_SPRING_BOOT_CLI_DIR=$APP_DIR/_spring-boot-cli
# APP_SPRING_BOOT_CLI_BIN_DIR=$APP_SPRING_BOOT_CLI_DIR/bin
# export PATH=$PATH:$APP_SPRING_BOOT_CLI_BIN_DIR

# https://www.mono-project.com/
# export MONO_HOME=/Library/Frameworks/Mono.framework/Versions/5.0.1
# export MONO_HOME_BIN=$MONO_HOME/bin
# export PATH=$PATH:$MONO_HOME_BIN


# https://docs.docker.com/engine/reference/commandline/cli/
# https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option
APP_DOCKER_DIR=$APP_DIR/_docker
CONFIG_DOCKER_DIR=$CONFIG_DIR/_docker
export PATH=$PATH:$APP_DOCKER_DIR
export DOCKER_HOST='tcp://127.0.0.1:2375'
export DOCKER_CONFIG=$CONFIG_DOCKER_DIR

# https://docs.docker.com/machine/
# https://docs.docker.com/machine/drivers/virtualbox/
# DATA_DOCKER_DIR=$DATA_DIR/_docker
#export DOCKER_HOME=$APP_DOCKER_DIR
#export MACHINE_STORAGE_PATH=$DATA_DOCKER_DIR
#export VIRTUALBOX_BOOT2DOCKER_URL=$DOCKER_HOME/boot2docker.iso
#export VIRTUALBOX_UI_TYPE=headless
#export VIRTUALBOX_CPU_COUNT=1
#export VIRTUALBOX_MEMORY_SIZE=512
#export VIRTUALBOX_DISK_SIZE=5120

# https://kubernetes.io/docs/tasks/tools/install-kubectl/
APP_KUBECTL_DIR=$APP_DIR/_kubectl
CONFIG_KUBECTL_DIR=$CONFIG_DIR/_kubectl
CONFIG_KUBECTL_CONFIG_FILE=$CONFIG_KUBECTL_DIR/config.yml
export KUBECONFIG=$CONFIG_KUBECTL_CONFIG_FILE
export PATH=$PATH:$APP_KUBECTL_DIR

# https://kubernetes.io/docs/tasks/tools/install-minikube/
# APP_MINIKUBE_DIR=$APP_DIR/_minikube
# DATA_MINIKUBE_DIR=$DATA_DIR/_minikube
# export MINIKUBE_HOME=$DATA_MINIKUBE_DIR
# export MINIKUBE_WANTUPDATENOTIFICATION=false
# export MINIKUBE_WANTREPORTERRORPROMPT=false
# export CHANGE_MINIKUBE_NONE_USER=true
# export PATH=$PATH:$APP_MINIKUBE_DIR

# https://helm.sh/docs
# https://github.com/helm/helm-www
# https://github.com/helm/helm/releases
APP_HELM_DIR=$APP_DIR/_helm
export PATH=$PATH:$APP_HELM_DIR

# https://github.com/mholt/caddy
# https://caddyserver.com/docs/cli
# APP_CADDY_DIR=$APP_DIR/_caddy
# export PATH=$PATH:$APP_CADDY_DIR

# https://github.com/v2ray/v2ray-core
APP_V2RAY_DIR=$APP_DIR/_v2ray
export PATH=$PATH:$APP_V2RAY_DIR


# https://www.rust-lang.org/
# https://github.com/rust-lang/rustup.rs#environment-variables
APP_RUSTUP_DIR=$APP_DIR/_rustup
export RUSTUP_HOME=$APP_RUSTUP_DIR
export RUSTUP_DIST_SERVER=http://mirrors.ustc.edu.cn/rust-static
export RUSTUP_UPDATE_ROOT=http://mirrors.ustc.edu.cn/rust-static/rustup
# https://github.com/rust-lang/cargo/blob/master/src/doc/src/reference/environment-variables.md
APP_CARGO_DIR=$APP_DIR/_cargo
APP_CARGO_BIN_DIR=$APP_CARGO_DIR/bin
export CARGO_HOME=$APP_CARGO_DIR
export PATH=$PATH:$APP_CARGO_BIN_DIR

# https://github.com/gohugoio/hugo
APP_HUGO_DIR=$APP_DIR/_hugo
CACHE_HUGO_DIR=$CACHE_DIR/_hugo
export PATH=$PATH:$APP_HUGO_DIR
export HUGO_CACHEDIR=$CACHE_HUGO_DIR

# https://nodejs.org/en/download/
APP_NODE_DIR=$APP_DIR/_node
APP_NODE_BIN_DIR=$APP_NODE_DIR/bin
export PATH=$PATH:$APP_NODE_BIN_DIR


# https://brew.sh
# https://github.com/Homebrew/brew
# https://developer.aliyun.com/mirror/homebrew
export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.aliyun.com/homebrew/homebrew-bottles


# https://www.db.com/download-center/community
APP_MONGO_DIR=$APP_DIR/_mongo
export PATH=$PATH:$APP_MONGO_DIR

# https://linianhui.github.io/redis/00-install
APP_REDIS_DIR=$APP_DIR/_redis
export PATH=$PATH:$APP_REDIS_DIR

# https://dev.mysql.com/downloads/mysql/
# https://dev.mysql.com/doc/refman/8.0/en/environment-variables.html
APP_MYSQL_DIR=$APP_DIR/_mysql
CACHE_MYSQL_CONFIG_DIR=$XDG_CACHE_HOME/_mysql
export MYSQL_HOME=$APP_MYSQL_DIR
APP_MYSQL_BIN_DIR=$MYSQL_HOME/bin
export MYSQL_HISTFILE=$CACHE_MYSQL_CONFIG_DIR/.history
export PATH=$PATH:$APP_MYSQL_BIN_DIR

# https://github.com/svenstaro/miniserve
APP_MINISERVE_DIR=$APP_DIR/_miniserve
export PATH=$PATH:$APP_MINISERVE_DIR

# http://www.rinetd.com/
# https://github.com/samhocevar/rinetd
APP_RINETD_DIR=$APP_DIR/_rinetd
export PATH=$PATH:$APP_RINETD_DIR

# https://github.com/wagoodman/dive
APP_DIVE_DIR=$APP_DIR/_dive
export PATH=$PATH:$APP_DIVE_DIR

# https://jmeter.apache.org/download_jmeter.cgi
APP_JMETER_DIR=$APP_DIR/_jmeter
APP_JMETER_BIN_DIR=$APP_JMETER_DIR/bin
export PATH=$PATH:$APP_JMETER_BIN_DIR

# iperf2 https://sourceforge.net/projects/iperf2/
# iperf3 https://iperf.fr/
APP_IPERF_DIR=$APP_DIR/_iperf
export PATH=$PATH:$APP_IPERF_DIR

# 杂项工具
APP_OTHER_DIR=$APP_DIR/_other
export PATH=$PATH:$APP_OTHER_DIR
#!/bin/sh

function __timestamp_2_iso8601(){
  timestampSecond=${1:0:10}
  millisecond=$(printf ".%03d" ${1:10:3})
  date "+%FT%T${millisecond}Z%:z" --date="@$timestampSecond"
}
declare -a __QUICK_ACCESS_DIRECTORY=()
__DELIMITER='.-_ ()'

function __directory_get_dir_name {
    path="$1:t"
    echo $path
}

function __directory_get_parent_dir_name {
    dir="$1"
    __directory_get_dir_name $(dirname "$dir")
}

function __directory_add_quick_access {
    dir="$1"
    delimiter=".-_ ()"
    if [ -f "$dir" ]; then
        echo "$dir is a file."
        return
    fi

    if [ -d "$dir" ]; then
        for subDir in $dir/*; do
            if [ -d "$subDir" ]; then
                subDirLowerCase=${subDir:l}
                name=$(__directory_get_dir_name $subDirLowerCase)
                parent=$(__directory_get_parent_dir_name $subDirLowerCase)
                nameAbbr=$(__string_abbr $name $__DELIMITER)
                parentAbbr=$(__string_abbr $parent $__DELIMITER)
                __QUICK_ACCESS_DIRECTORY+="$nameAbbr $parentAbbr$nameAbbr $subDirLowerCase $subDir"
            fi
        done
    else
        echo "$dir is not exist."
    fi
}


function __directory_list_quick_access {
    print -l $__QUICK_ACCESS_DIRECTORY
}

function __directory_search_quick_access {
    result=''
    __directory_search_quick_access_core "$1" | sort -k1nr | while read line
    do
        result="$result${line:2} "
    done
    echo $result
}

function __directory_search_quick_access_core {
    search="$1"
    for line in $__QUICK_ACCESS_DIRECTORY; do
        result=$(__directory_search_quick_access_core_line $line $search)
        if [[ "$result" != "" ]]; then
            echo "$result"
        fi
    done
}

function __directory_search_quick_access_core_line {
    line="$1"
    search="$2"
    cols=($(echo $line))

    contains=$(__string_contains $cols[1] $search)
    if (( $contains == 0 )); then
        echo "9 $cols[4]"
        return
    fi

    contains=$(__string_contains $cols[2] $search)
    if (( $contains == 0 )); then
        echo "8 $cols[4]"
        return
    fi

    contains=$(__string_contains $cols[3] $search)
    if (( $contains == 0 )); then
        echo "7 $cols[4]"
        return
    fi

    contains=$(__string_match $cols[3] $search)
    if (( $contains == 0 )); then
        echo "6 $cols[4]"
        return
    fi
}

function __directory_to {
    dir="$@[$#]"
    echo "cd $dir"
    cd "$dir"
}

function __directory_search_quick_access_complete {
    cols=($(__directory_search_quick_access $words[2]))
    _alternative "dir:dir:($cols)"
}
function __git_warn_gc () {
    echo -e "\033[32mgit reflog expire --expire=now --all \033[0m"
    git warn-expire-reflog
    echo -e "\033[32mgit gc --prune=now --aggressive \033[0m"
    git warn-gc-now
    echo -e "\033[32mgit count-objects -v -H \033[0m"
    git size
}

function __git_proxy(){
    local action=${1:-get}

    if [ $action = 'set' ] ;then
        git config --global http.proxy 'socks5://127.0.0.1:1080'
    fi

    if [ $action = 'unset' ] ;then
        git config --global --unset http.proxy
    fi

    git config --global --get http.proxy
}
function __proc_env(){
    cat /proc/$1/environ | tr '\0' '\n' | sort
}

function __proc_env2(){
    ps ewww -o command $1 | tr ' ' '\n' | sort
}
#!/bin/zsh

# example : __string_contains abc bc
function __string_contains {
    if [[ "$1" == *$2* ]]; then
        echo 0
        return
    fi
    echo 1
}

# example : __string_match abc ac
function __string_match {
    str="$1"
    subStr="$2"
    subStrLen=${#subStr}
    for i ({1..$subStrLen}) {
        char=$subStr[$i]
        strLen=${#str}
        strIndex=1
        strIndex=$str[(i)$char]
        if (( $strIndex > $strLen )) then
            echo 1
            return
        else
            str=${str:$strIndex}
        fi
    }
    echo 0
}

# example : __string_split 'abc-123.456_asd' '-_.'
function __string_split {
    echo ${1//[$2]/ }
}

# example : __string_abbr abc-def '-'
function __string_abbr {
    abbr=""
    for word in $(echo ${1//[$2]/ }); do
        abbr="$abbr${word:0:1}"
    done
    echo "$abbr"
}

function __string_test {
    actual=$(__string_contains abc bc)
    expect=0
    ok=$(__if_then_else $actual $expect $__TEST_OK_STRING $__TEST_FAIL_STRING)
    echo -e "test : __string_contains abc bc $ok"

    actual=$(__string_match abc ac)
    expect=0
    ok=$(__if_then_else $actual $expect $__TEST_OK_STRING $__TEST_FAIL_STRING)
    echo -e "test : __string_match abc ac $ok"

    actual=$(__string_split abc-123.456_asd -_.)
    expect='abc 123 456 asd'
    ok=$(__if_then_else $actual $expect $__TEST_OK_STRING $__TEST_FAIL_STRING)
    echo -e "test : __string_split abc-123.456_asd -_. $ok"

    actual=$(__string_abbr abc-def -)
    expect=ad
    ok=$(__if_then_else $actual $expect $__TEST_OK_STRING $__TEST_FAIL_STRING)
    echo -e "test : __string_abbr abc-def - $ok"
}

#!/bin/zsh

__TEST_OK_STRING='\033[32mok\033[0m'
__TEST_FAIL_STRING='\033[31mfail\033[0m'

function __if_then_else {
    if [[ "$1" == "$2" ]]; then
        echo "$3"
    else
        echo "$4"
    fi
}

function __port(){
    lsof "-i:$1"
}
# bash/zsh git prompt support
#
# Copyright (C) 2018 David Xu
#
# Based on the earlier work by Shawn O. Pearce <spearce@spearce.org>
# Distributed under the GNU General Public License, version 2.0.
#
# This script allows you to see the current branch in your prompt,
# posh-git style.
#
# You will most likely want to make use of either `__posh_git_ps1` or
# `__posh_git_echo`. Refer to the documentation of the functions for additional
# information.
#
#
# CONFIG OPTIONS
# ==============
#
# This script should work out of the box. Available options are set through
# your git configuration files. This allows you to control the prompt display on a
# per-repository basis.
# ```
# bash.describeStyle
# bash.enableFileStatus
# bash.enableGitStatus
# bash.showStatusWhenZero
# bash.showUpstream
# ```
#
# bash.describeStyle
# ------------------
#
# This option controls if you would like to see more information about the
# identity of commits checked out as a detached `HEAD`. This is also controlled
# by the legacy environment variable `GIT_PS1_DESCRIBESTYLE`.
#
# Option   | Description
# -------- | -----------
# contains | relative to newer annotated tag `(v1.6.3.2~35)`
# branch   | relative to newer tag or branch `(master~4)`
# describe | relative to older annotated tag `(v1.6.3.1-13-gdd42c2f)`
# default  | exactly matching tag
#
# bash.enableFileStatus
# ---------------------
#
# Option | Description
# ------ | -----------
# true   | _Default_. The script will query for all file indicators every time.
# false  | No file indicators will be displayed. The script will not query
#          upstream for differences. Branch color-coding information is still
#          displayed.
#
# bash.enableGitStatus
# --------------------
#
# Option | Description
# ------ | -----------
# true   | _Default_. Color coding and indicators will be shown.
# false  | The script will not run.
#
# bash.showStashState
# -------------------
#
# Option | Description
# ------ | -----------
# true   | _Default_. An indicator will display if the stash is not empty.
# false  | An indicator will not display the stash status.
#
# bash.showStatusWhenZero
# -----------------------
#
# Option | Description
# ------ | -----------
# true   | Indicators will be shown even if there are no updates to the index or
#          working tree.
# false  | _Default_. No file change indicators will be shown if there are no
#          changes to the index or working tree.
#
# bash.showUpstream
# -----------------
#
# By default, `__posh_git_ps1` will compare `HEAD` to your `SVN` upstream if it can
# find one, or `@{upstream}` otherwise. This is also controlled by the legacy
# environment variable `GIT_PS1_SHOWUPSTREAM`.
#
# Option | Description
# ------ | -----------
# legacy | Does not use the `--count` option available in recent versions of
#          `git-rev-list`
# git    | _Default_. Always compares `HEAD` to `@{upstream}`
# svn    | Always compares `HEAD` to `SVN` upstream
#
# bash.enableStatusSymbol
# -----------------------

# Option | Description
# ------ | -----------
# true   | _Default_. Status symbols (`≡` `↑` `↓` `↕`) will be shown.
# false  | No status symbol will be shown, saving some prompt length.
#
###############################################################################

# Convenience function to set PS1 to show git status. Must supply two
# arguments that specify the prefix and suffix of the git status string.
#
# This function should be called in PROMPT_COMMAND or similar.
__posh_git_ps1 ()
{
    local ps1pc_prefix=
    local ps1pc_suffix=
    case "$#" in
        2)
            ps1pc_prefix=$1
            ps1pc_suffix=$2
            ;;
        *)
            echo __posh_git_ps1: bad number of arguments >&2
            return
            ;;
    esac
    local gitstring=$(__posh_git_echo)
    PS1=$ps1pc_prefix$gitstring$ps1pc_suffix
}

__posh_color () {
    if [ -n "$ZSH_VERSION" ]; then
        echo %{$1%}
    elif [ -n "$BASH_VERSION" ]; then
        echo \\[$1\\]
    else
        # assume Bash anyway
        echo \\[$1\\]
    fi
}

# Echoes the git status string.
__posh_git_echo () {
    if [ "$(git config --bool bash.enableGitStatus)" = 'false' ]; then
        return;
    fi

    local DefaultForegroundColor=$(__posh_color '\e[m') # Default no color
    local DefaultBackgroundColor=

    local BeforeText='['
    local BeforeForegroundColor=$(__posh_color '\e[1;33m') # Yellow
    local BeforeBackgroundColor=
    local DelimText=' |'
    local DelimForegroundColor=$(__posh_color '\e[1;33m') # Yellow
    local DelimBackgroundColor=

    local AfterText=']'
    local AfterForegroundColor=$(__posh_color '\e[1;33m') # Yellow
    local AfterBackgroundColor=

    local BranchForegroundColor=$(__posh_color '\e[1;36m')  # Cyan
    local BranchBackgroundColor=
    local BranchAheadForegroundColor=$(__posh_color '\e[1;32m') # Green
    local BranchAheadBackgroundColor=
    local BranchBehindForegroundColor=$(__posh_color '\e[0;31m') # Red
    local BranchBehindBackgroundColor=
    local BranchBehindAndAheadForegroundColor=$(__posh_color '\e[1;33m') # Yellow
    local BranchBehindAndAheadBackgroundColor=

    local BeforeIndexText=''
    local BeforeIndexForegroundColor=$(__posh_color '\e[1;32m') # Dark green
    local BeforeIndexBackgroundColor=

    local IndexForegroundColor=$(__posh_color '\e[1;32m') # Dark green
    local IndexBackgroundColor=

    local WorkingForegroundColor=$(__posh_color '\e[0;31m') # Dark red
    local WorkingBackgroundColor=

    local StashForegroundColor=$(__posh_color '\e[0;34m') # Darker blue
    local StashBackgroundColor=
    local StashText='$'

    local RebaseForegroundColor=$(__posh_color '\e[0m') # reset
    local RebaseBackgroundColor=

    local EnableFileStatus=`git config --bool bash.enableFileStatus`
    case "$EnableFileStatus" in
        true)  EnableFileStatus=true ;;
        false) EnableFileStatus=false ;;
        *)     EnableFileStatus=true ;;
    esac
    local ShowStatusWhenZero=`git config --bool bash.showStatusWhenZero`
    case "$ShowStatusWhenZero" in
        true)  ShowStatusWhenZero=true ;;
        false) ShowStatusWhenZero=false ;;
        *)     ShowStatusWhenZero=false ;;
    esac
    local ShowStashState=`git config --bool bash.showStashState`
    case "$ShowStashState" in
        true)  ShowStashState=true ;;
        false) ShowStashState=false ;;
        *)     ShowStashState=true ;;
    esac
    local EnableStatusSymbol=`git config --bool bash.enableStatusSymbol`
    case "$EnableStatusSymbol" in
        true)  EnableStatusSymbol=true ;;
        false) EnableStatusSymbol=false ;;
        *)     EnableStatusSymbol=true ;;
    esac

    local BranchIdenticalStatusSymbol=''
    local BranchAheadStatusSymbol=''
    local BranchBehindStatusSymbol=''
    local BranchBehindAndAheadStatusSymbol=''
    local BranchWarningStatusSymbol=''
    if $EnableStatusSymbol; then
      BranchIdenticalStatusSymbol=$' \xE2\x89\xA1' # Three horizontal lines
      BranchAheadStatusSymbol=$' \xE2\x86\x91' # Up Arrow
      BranchBehindStatusSymbol=$' \xE2\x86\x93' # Down Arrow
      BranchBehindAndAheadStatusSymbol=$' \xE2\x86\x95' # Up and Down Arrow
      BranchWarningStatusSymbol=' ?'
    fi

    # these globals are updated by __posh_git_ps1_upstream_divergence
    __POSH_BRANCH_AHEAD_BY=0
    __POSH_BRANCH_BEHIND_BY=0

    local is_detached=false

    local g=$(__posh_gitdir)
    if [ -z "$g" ]; then
        return # not a git directory
    fi
    local rebase=''
    local b=''
    local step=''
    local total=''
    if [ -d "$g/rebase-merge" ]; then
        b=$(cat "$g/rebase-merge/head-name" 2>/dev/null)
        step=$(cat "$g/rebase-merge/msgnum" 2>/dev/null)
        total=$(cat "$g/rebase-merge/end" 2>/dev/null)
        if [ -f "$g/rebase-merge/interactive" ]; then
            rebase='|REBASE-i'
        else
            rebase='|REBASE-m'
        fi
    else
        if [ -d "$g/rebase-apply" ]; then
            step=$(cat "$g/rebase-apply/next")
            total=$(cat "$g/rebase-apply/last")
            if [ -f "$g/rebase-apply/rebasing" ]; then
                rebase='|REBASE'
            elif [ -f "$g/rebase-apply/applying" ]; then
                rebase='|AM'
            else
                rebase='|AM/REBASE'
            fi
        elif [ -f "$g/MERGE_HEAD" ]; then
            rebase='|MERGING'
        elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
            rebase='|CHERRY-PICKING'
        elif [ -f "$g/REVERT_HEAD" ]; then
            rebase='|REVERTING'
        elif [ -f "$g/BISECT_LOG" ]; then
            rebase='|BISECTING'
        fi

        b=$(git symbolic-ref HEAD 2>/dev/null) || {
            is_detached=true
            local output=$(git config -z --get bash.describeStyle)
            if [ -n "$output" ]; then
                GIT_PS1_DESCRIBESTYLE=$output
            fi
            b=$(
            case "${GIT_PS1_DESCRIBESTYLE-}" in
            (contains)
                git describe --contains HEAD ;;
            (branch)
                git describe --contains --all HEAD ;;
            (describe)
                git describe HEAD ;;
            (* | default)
                git describe --tags --exact-match HEAD ;;
            esac 2>/dev/null) ||

            b=$(cut -c1-7 "$g/HEAD" 2>/dev/null)... ||
            b='unknown'
            b="($b)"
        }
    fi

    if [ -n "$step" ] && [ -n "$total" ]; then
        rebase="$rebase $step/$total"
    fi

    local hasStash=false
    local isBare=''

    if [ 'true' = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
        if [ 'true' = "$(git rev-parse --is-bare-repository 2>/dev/null)" ]; then
            isBare='BARE:'
        else
            b='GIT_DIR!'
        fi
    elif [ 'true' = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
        if $ShowStashState; then
            git rev-parse --verify refs/stash >/dev/null 2>&1 && hasStash=true
        fi
        __posh_git_ps1_upstream_divergence
        local divergence_return_code=$?
    fi

    # show index status and working directory status
    if $EnableFileStatus; then
        local indexAdded=0
        local indexModified=0
        local indexDeleted=0
        local indexUnmerged=0
        local filesAdded=0
        local filesModified=0
        local filesDeleted=0
        local filesUnmerged=0
        while IFS="\n" read -r tag rest
        do
            case "${tag:0:1}" in
                A )
                    (( indexAdded++ ))
                    ;;
                M )
                    (( indexModified++ ))
                    ;;
                R )
                    (( indexModified++ ))
                    ;;
                C )
                    (( indexModified++ ))
                    ;;
                D )
                    (( indexDeleted++ ))
                    ;;
                U )
                    (( indexUnmerged++ ))
                    ;;
            esac
            case "${tag:1:1}" in
                \? )
                    (( filesAdded++ ))
                    ;;
                A )
                    (( filesAdded++ ))
                    ;;
                M )
                    (( filesModified++ ))
                    ;;
                D )
                    (( filesDeleted++ ))
                    ;;
                U )
                    (( filesUnmerged++ ))
                    ;;
            esac
        done <<< "`git status --porcelain 2>/dev/null`"
    fi

    local gitstring=
    local branchstring="$isBare${b##refs/heads/}"

    # before-branch text
    gitstring="$BeforeBackgroundColor$BeforeForegroundColor$BeforeText"

    # branch
    if (( $__POSH_BRANCH_BEHIND_BY > 0 && $__POSH_BRANCH_AHEAD_BY > 0 )); then
        gitstring+="$BranchBehindAndAheadBackgroundColor$BranchBehindAndAheadForegroundColor$branchstring$BranchBehindAndAheadStatusSymbol"
    elif (( $__POSH_BRANCH_BEHIND_BY > 0 )); then
        gitstring+="$BranchBehindBackgroundColor$BranchBehindForegroundColor$branchstring$BranchBehindStatusSymbol"
    elif (( $__POSH_BRANCH_AHEAD_BY > 0 )); then
        gitstring+="$BranchAheadBackgroundColor$BranchAheadForegroundColor$branchstring$BranchAheadStatusSymbol"
    elif (( $divergence_return_code )); then
        # ahead and behind are both 0, but there was some problem while executing the command.
        gitstring+="$BranchBackgroundColor$BranchForegroundColor$branchstring$BranchWarningStatusSymbol"
    else
        # ahead and behind are both 0, and the divergence was determined successfully
        gitstring+="$BranchBackgroundColor$BranchForegroundColor$branchstring$BranchIdenticalStatusSymbol"
    fi

    # index status
    if $EnableFileStatus; then
        local indexCount="$(( $indexAdded + $indexModified + $indexDeleted + $indexUnmerged ))"
        local workingCount="$(( $filesAdded + $filesModified + $filesDeleted + $filesUnmerged ))"
        if (( $indexCount != 0 )) || $ShowStatusWhenZero; then
            gitstring+="$IndexBackgroundColor$IndexForegroundColor +$indexAdded ~$indexModified -$indexDeleted"
        fi
        if (( $indexUnmerged != 0 )); then
            gitstring+=" $IndexBackgroundColor$IndexForegroundColor!$indexUnmerged"
        fi
        if (( $indexCount != 0 && ($workingCount != 0 || $ShowStatusWhenZero) )); then
            gitstring+="$DelimBackgroundColor$DelimForegroundColor$DelimText"
        fi
        if (( $workingCount != 0 )) || $ShowStatusWhenZero; then
            gitstring+="$WorkingBackgroundColor$WorkingForegroundColor +$filesAdded ~$filesModified -$filesDeleted"
        fi
        if (( $filesUnmerged != 0 )); then
            gitstring+=" $WorkingBackgroundColor$WorkingForegroundColor!$filesUnmerged"
        fi
    fi
    gitstring+="${rebase:+$RebaseForegroundColor$RebaseBackgroundColor$rebase}"

    # after-branch text
    gitstring+="$AfterBackgroundColor$AfterForegroundColor$AfterText"

    if $ShowStashState && $hasStash; then
        gitstring+="$StashBackgroundColor$StashForegroundColor"$StashText
    fi
    gitstring+="$DefaultBackgroundColor$DefaultForegroundColor"
    echo "$gitstring"
}

# Returns the location of the .git/ directory.
__posh_gitdir ()
{
    # Note: this function is duplicated in git-completion.bash
    # When updating it, make sure you update the other one to match.
    if [ -z "${1-}" ]; then
        if [ -n "${__posh_git_dir-}" ]; then
            echo "$__posh_git_dir"
        elif [ -n "${GIT_DIR-}" ]; then
            test -d "${GIT_DIR-}" || return 1
            echo "$GIT_DIR"
        elif [ -d .git ]; then
            echo .git
        else
            git rev-parse --git-dir 2>/dev/null
        fi
    elif [ -d "$1/.git" ]; then
        echo "$1/.git"
    else
        echo "$1"
    fi
}

# Updates the global variables `__POSH_BRANCH_AHEAD_BY` and `__POSH_BRANCH_BEHIND_BY`.
__posh_git_ps1_upstream_divergence ()
{
    local key value
    local svn_remote svn_url_pattern
    local upstream=git          # default
    local legacy=''

    svn_remote=()
    # get some config options from git-config
    local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showUpstream)$' 2>/dev/null | tr '\0\n' '\n ')"
    while read -r key value; do
        case "$key" in
        bash.showUpstream)
            GIT_PS1_SHOWUPSTREAM="$value"
            if [ -z "${GIT_PS1_SHOWUPSTREAM}" ]; then
                return
            fi
            ;;
        svn-remote.*.url)
            svn_remote[ $((${#svn_remote[@]} + 1)) ]="$value"
            svn_url_pattern+="\\|$value"
            upstream=svn+git # default upstream is SVN if available, else git
            ;;
        esac
    done <<< "$output"

    # parse configuration values
    for option in ${GIT_PS1_SHOWUPSTREAM}; do
        case "$option" in
        git|svn) upstream="$option" ;;
        legacy)  legacy=1  ;;
        esac
    done

    # Find our upstream
    case "$upstream" in
    git)    upstream='@{upstream}' ;;
    svn*)
        # get the upstream from the "git-svn-id: ..." in a commit message
        # (git-svn uses essentially the same procedure internally)
        local svn_upstream=($(git log --first-parent -1 \
                    --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
        if (( 0 != ${#svn_upstream[@]} )); then
            svn_upstream=${svn_upstream[ ${#svn_upstream[@]} - 2 ]}
            svn_upstream=${svn_upstream%@*}
            local n_stop="${#svn_remote[@]}"
            local n
            for ((n=1; n <= n_stop; n++)); do
                svn_upstream=${svn_upstream#${svn_remote[$n]}}
            done

            if [ -z "$svn_upstream" ]; then
                # default branch name for checkouts with no layout:
                upstream=${GIT_SVN_ID:-git-svn}
            else
                upstream=${svn_upstream#/}
            fi
        elif [ 'svn+git' = "$upstream" ]; then
            upstream='@{upstream}'
        fi
        ;;
    esac

    local return_code=
    __POSH_BRANCH_AHEAD_BY=0
    __POSH_BRANCH_BEHIND_BY=0
    # Find how many commits we are ahead/behind our upstream
    if [ -z "$legacy" ]; then
        local output=
        output=$(git rev-list --count --left-right $upstream...HEAD 2>/dev/null)
        return_code=$?
        IFS=$' \t\n' read -r __POSH_BRANCH_BEHIND_BY __POSH_BRANCH_AHEAD_BY <<< $output
    else
        local output
        output=$(git rev-list --left-right $upstream...HEAD 2>/dev/null)
        return_code=$?
        # produce equivalent output to --count for older versions of git
        while IFS=$' \t\n' read -r commit; do
            case "$commit" in
            "<*") (( __POSH_BRANCH_BEHIND_BY++ )) ;;
            ">*") (( __POSH_BRANCH_AHEAD_BY++ ))  ;;
            esac
        done <<< $output
    fi
    : ${__POSH_BRANCH_AHEAD_BY:=0}
    : ${__POSH_BRANCH_BEHIND_BY:=0}
    return $return_code
}
function __idea_open {
    dir="$@[$#]"
    echo "idea $dir"
    idea "$dir"
}
autoload -Uz compinit && compinit

source $(dirname $0)/a.sh

# https://adoptium.net/temurin/releases?version=11
# tar xvf openjdk.tar.gz /lnh/_app/_java11
# export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8
# cd /Library/Java/JavaVirtualMachines
# sudo ln shf /lnh/_app/_java8 java8
# sudo ln shf /lnh/_app/_java11 java11
# sudo ln shf /lnh/_app/_java17 java17
# sudo ln shf /lnh/_app/_java21 java21
export JAVA_8_HOME=`/usr/libexec/java_home -v 1.8`
export JAVA_11_HOME=`/usr/libexec/java_home -v 11`
export JAVA_17_HOME=`/usr/libexec/java_home -v 17`
export JAVA_21_HOME=`/usr/libexec/java_home -v 21`
export JAVA_HOME=$JAVA_8_HOME

launchctl setenv JAVA_HOME $JAVA_HOME

launchctl setenv M2_HOME $M2_HOME
launchctl setenv MAVEN_HOME $MAVEN_HOME
launchctl setenv MAVEN_OPTS $MAVEN_OPTS

launchctl setenv GRADLE_HOME $GRADLE_HOME
launchctl setenv GRADLE_USER_HOME $GRADLE_USER_HOME

# https://github.com/ggreer/lscolors
export CLICOLOR=1

__directory_add_quick_access /lnh
__directory_add_quick_access /lnh/_code
__directory_add_quick_access /lnh/_github
#__directory_add_to_quick_access /lnh/_app

if [ -f "/lnh/_shell/a.sh" ]; then
  source /lnh/_shell/a.sh
fi
function __vscode_open {
    dir="$@[$#]"
    echo "code $dir"
    code "$dir"
}
setopt completealiases
compdef __directory_search_quick_access_complete c
compdef __directory_search_quick_access_complete d
compdef __directory_search_quick_access_complete i
# zsh              http://www.zsh.org/
# precmd           http://zsh.sourceforge.net/Doc/Release/Functions.html#Hook-Functions
# Prompt-Expansion http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Prompt-Expansion
# __posh_git_echo  https://github.com/lyze/posh-git-sh

unsetopt PROMPT_SP
setopt prompt_subst
# RPROMPT="[%(?.%F{green}%?%f.%F{red}%?%f)]"

precmd(){
  USER_TYPE='%(!.#.$)'
  NEW_LINE=$'\n'
  LAST_EXIT_CODE="%(?..%F{red}%?%f)"
  TIME=$(gdate +'%y-%m-%d %T %:z %s%3N w%u d%-j')
  COMMON_PROMPT='$NEW_LINE%F{green}$USER_TYPE%f %n@%m %d $TIME $LAST_EXIT_CODE'
  INPUT_PROMPT='$NEW_LINE'
  if git rev-parse --git-dir > /dev/null 2>&1; then
    GIT_USER="$(git config user.name)@<$(git config user.email)>"
    GIT_PROMPT='$NEW_LINE%F{green}$USER_TYPE $GIT_USER%f %F{red}%1d%f $(__posh_git_echo)'
    PROMPT="$COMMON_PROMPT $GIT_PROMPT $INPUT_PROMPT"
  else
    PROMPT="$COMMON_PROMPT $INPUT_PROMPT"
  fi
}
下一篇 : [Linux] SSH