### Nurza's zshrc export ZSHRC_TYPE=metal export ZSHRC_VERSION=26.1 ## Auto completion autoload -Uz compinit compinit ## If not running interactively, do nothing [ -z "$PS1" ] && return ## Emacs style key bindings bindkey -e bindkey '^[[1;5C' emacs-forward-word bindkey '^[[1;5D' emacs-backward-word stty -ixon # # Get the sorted size of directories and files in a directory # Usage: dush [path] # function dush { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi unsetopt nomatch ls "$1"/.* &> /dev/null if [ $? -eq 0 ] ; then du -sh "$1"/* "$1"/.* |sort -h else du -sh "$1"/*|sort -h fi setopt nomatch } # # Copy a file or directory to make a backup # Usage: bak [path] # function bak { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi cp -rp "$1" "$1_`date +%Y-%m-%d_%H-%M%:::z`" } # # Move a file or directory to make a backup # Usage: old [path] # function old { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi mv "$1" "$1_`date +%Y-%m-%d_%H-%M%:::z`" } # # Encrypt a file # Usage: encrypt [path] # function encrypt { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi if [ ! -f "${1}" ] then echo "File ${1} not found" return 2 fi if openssl version | grep "OpenSSL 1.1" &> /dev/null then cypher="-pbkdf2" else cypher="" fi openssl enc -aes-256-cbc "${cypher}" -in "${1}" -out "${1}.enc" } # # decrypt a file # Usage: decrypt [path] # function decrypt { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi if [ ! -f "${1}" ] then echo "File ${1} not found" return 2 fi if [[ ! "${1}" =~ \.enc$ ]] then echo "File ${1} is not a .enc file" return 3 fi out=$(echo "${1}" | sed 's/\.enc$//g') if [ -f "${out}" ] then echo "File ${out} already exists" return 4 fi if openssl version | grep "OpenSSL 1.1" &> /dev/null then cypher="-pbkdf2" else cypher="" fi openssl enc -d -aes-256-cbc "${cypher}" -in "${1}" -out "${out}" } # # compress a file # Usage: compress [path] # function compress { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi if [ ! -f "${1}" ] then echo "File ${1} not found" return 2 fi out=$(echo "${1}.xz") if [ -f "${out}" ] then echo "File ${out} already exists" return 4 fi xz -z1 --block-size=1MiB -T$(nproc) ${1} } # # Create a directory and set as working directory # Usage: mkcd [path] # function mkcd { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi mkdir -p "$1" cd "$1" } # # Set an network interface down and up # Usage: ifdu [interface] # function ifdu { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi ifdown "$1"; ifup "$1" } # # Run an interactive zsh shell in a Docker container # Usage: dzsh [container name] # function dzsh { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi docker exec -it "$1" zsh } # # Run an interactive zsh shell in a Kubernetes container # Usage: kzsh [container name] # function kzsh { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi kubectl exec -it "$1" zsh } # # Run an interactive bash shell in a Kubernetes container # Usage: kbash [container name] # function kbash { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi kubectl exec -it "$1" bash } # # Run an interactive sh shell in a Kubernetes container # Usage: dsh [container name] # function ksh { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi kubectl exec -it "$1" sh } # # Fast usage of the command "youtube-dl" # Usage: ydl # function ydl { echo -n "YouTube URL: " read -s YURL youtube-dl "$YURL" } # # Make a tarball from a target # Usage: tarball [path] # function tarball { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi tar c "$1" | gzip -1 > "$1_`date +%Y-%m-%d_%H-%M%:::z`.tar.gz" } # # Update the current zshrc # Usage: zshrc-update # function zshrc-update { RC_LOCATION="https://files.nurza.fr/rc" STATUS_CODE=$(wget --spider -S "$RC_LOCATION/zshrc-$ZSHRC_TYPE" 2>&1 | grep "HTTP/" | head -1 | awk '{print $2}') if [ "$STATUS_CODE" -ne 200 ] then echo "Update canceled : update server returned a non 200 http status code : $STATUS_CODE" return 1 fi wget -O "$HOME/.zshrc" "$RC_LOCATION/zshrc-$ZSHRC_TYPE" zsh } # # Update the current vimrc # Usage: vimrc-update # function vimrc-update { RC_LOCATION="https://files.nurza.fr/rc" STATUS_CODE=$(wget --spider -S "$RC_LOCATION/vimrc" 2>&1 | grep "HTTP/" | head -1 | awk '{print $2}') if [ "$STATUS_CODE" -ne 200 ] then echo "Update canceled : update server returned a non 200 http status code : $STATUS_CODE" return 1 fi mkdir -p "$HOME/.vim/colors" mkdir -p "$HOME/.vim/syntax" wget -O "$HOME/.vimrc" "$RC_LOCATION/vimrc" wget -O "$HOME/.vim/colors/molokai.vim" "$RC_LOCATION/molokai.vim" wget -O "$HOME/.vim/syntax/haproxy.vim" "$RC_LOCATION/haproxy.vim" } # # Update the current htoprc # Usage: htoprc-update # function htoprc-update { RC_LOCATION="https://files.nurza.fr/rc" STATUS_CODE=$(wget --spider -S "$RC_LOCATION/htoprc" 2>&1 | grep "HTTP/" | head -1 | awk '{print $2}') if [ "$STATUS_CODE" -ne 200 ] then echo "Update canceled : update server returned a non 200 http status code : $STATUS_CODE" return 1 fi mkdir -p "$HOME/.config/htop/" wget -O "$HOME/.config/htop/htoprc" "$RC_LOCATION/htoprc" } # # List IP address of all Docker containers # Usage: dip # function dip { for cid in $(docker ps -qa) do DIP=$(docker inspect $cid|grep IPAddress|cut -d '"' -f 4|tr "\n" " ") DNAME=$(docker inspect --format '{{ .Config.Hostname }}' $cid) echo "$DIP\t$cid\t$DNAME " done } # # List usb inputs # Usage: lsinput # function lsinput { for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do ( syspath="${sysdevpath%/dev}" devname="$(udevadm info -q name -p $syspath)" [[ "$devname" == "bus/"* ]] && continue eval "$(udevadm info -q property --export -p $syspath)" [[ -z "$ID_SERIAL" ]] && continue echo "/dev/$devname - $ID_SERIAL" ) done } # # Print iptables in a sweat way to easily understand rules # Usage: iptp # function iptp { if [[ $# -eq 0 ]]; then iptables -L -n -v --line-number elif [[ $1 = "nat" ]]; then iptables -t $1 -L -n -v --line-number elif [[ $1 = "mangle" ]]; then iptables -t $1 -L -n -v --line-number else echo "usage -> iptp {nat|mangle}" fi } # # Print file and add an extra line end # Usage: cate [file path] # function cate { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi cat "$1" ; echo } function pkgname { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi dpkg -S $(whereis $1 | cut -d " " -f 2) } # # # # function kn { kubectl config set-context $(kubectl config current-context) --namespace=$1 } # # # # function kzg { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi kubectl exec -it "$(kubectl get pods | grep $1 | awk '{print $1}' | head -1)" zsh } # # # # function kgpgrep { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi kubectl get pods | grep "$1" | awk '{print $1}' } # # # # function kgpgrepa { if [ -z ${1+x} ] then echo "Parameter is unset" return 1 fi kubectl get pods --all-namespaces | grep "$1" | awk '{print $1}' } # # # # function ysel { if [ -z ${2+x} ] then echo "Parameters are unset" return 1 fi cat $1 | yq -s ".[$2]" --yaml-output } # Checks if working tree is dirty for prompt function parse_git_dirty() { local STATUS='' local FLAGS FLAGS=('--porcelain') if [[ "$(command git config --get oh-my-zsh.hide-dirty)" != "1" ]]; then if [[ $POST_1_7_2_GIT -gt 0 ]]; then FLAGS+='--ignore-submodules=dirty' fi if [[ "$DISABLE_UNTRACKED_FILES_DIRTY" == "true" ]]; then FLAGS+='--untracked-files=no' fi STATUS=$(command git status ${FLAGS} 2> /dev/null | tail -n1) fi if [[ -n $STATUS ]]; then echo "$ZSH_THEME_GIT_PROMPT_DIRTY" else echo "$ZSH_THEME_GIT_PROMPT_CLEAN" fi } # Display git custom status for prompt function git_custom_status { # Set terminal title echo -ne "\033]0;$(id -un)@$(hostname):$(pwd)\007" which git > /dev/null if [ "$?" -ne 0 ] then return 1 fi cb="$(git branch 2> /dev/null | sed -n '/\* /s///p'| tr -d '('| tr -d ')')" if [ -n "$cb" ]; then nbcommit=$(git status|grep 'Your branch is ahead of'|cut -d "'" -f 3|awk '{print $2}') if [ -n "$nbcommit" ]; then nbc=" $fg_bold[white]%}\u26a1%{$reset_color%}$fg[green]%} $nbcommit" fi echo " $(parse_git_dirty)%{$reset_color%}%{$fg_bold[red]%}$ZSH_THEME_GIT_PROMPT_PREFIX$cb$nbc$ZSH_THEME_GIT_PROMPT_SUFFIX" fi } # Display Docker custom status for prompt function docker_custom_status { which docker > /dev/null if [ "$?" -ne 0 ] then return 1 fi DPSA=$(timeout 0.5 docker ps -a --format "{{.Status}}" 2> /dev/null) if [ "$?" -ne 0 ] then DOWN="$fg[red]%}docker too slow" echo " %{$fg[blue]%}[$DOWN%{$fg[blue]%}]" return 4 fi DPCAWC=$(echo $DPSA|wc -l) UP=$(echo -n $DPSA|grep "Up"|wc -l) DOWN=$(($DPCAWC-$UP)) if [ "$DPSA" = "" ] ; then return 2 fi if [ $UP -ne 0 ] ; then UP="$fg[green]%}●$UP" else UP="" fi if [ $DOWN -ne 0 ] ; then DOWN="$fg[red]%}✖$DOWN" else DOWN="" fi if [ "$UP" = "" ] && [ "$DOWN" = "" ] ; then return 3 fi if [ "$UP" != "" ] && [ "$DOWN" != "" ] ; then DSPACE=" " else DSPACE="" fi echo " %{$fg[blue]%}[$UP$DSPACE$DOWN%{$fg[blue]%}]" } # Display Kubernetes custom status for prompt function k8s_custom_status { which kubeadm > /dev/null if [ "$?" -ne 0 ] then return 1 fi if [ ! -f /etc/kubernetes/admin.conf ] then return 1 fi CURRENT_NAMESPACE=$(cat /etc/kubernetes/admin.conf | grep namespace | cut -d ' ' -f 6) echo " %{$fg[cyan]%}[\u2638 $CURRENT_NAMESPACE%{$fg[cyan]%}]" } ## Variables export EDITOR='vim' export LANG=en_US.UTF-8 export PAGE=most export MANPAGER=most export PATH=$PATH:/usr/local/go/bin:~/gopath/bin:/usr/local/cuda/bin:/sbin export GOPATH=$HOME/gopath export GOMAXPROCS=$(grep -c ^processor /proc/cpuinfo) export TERM=xterm-256color export WORDCHARS='*?_-+.[]~=&;!#$%^(){}<>' # Numlock numlockx 2> /dev/null ## History export HISTFILE=~/.zshhistory export HISTSIZE=1000000 export SAVEHIST=$HISTSIZE setopt hist_ignore_dups extended_history inc_append_history no_hist_beep prompt_subst setopt appendhistory setopt incappendhistory ## Completion settings # from compinstall zstyle ':completion:*' completer _expand _complete _correct zstyle ':completion:*' list '' #list-color for colored completion zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=** r:|=**' zstyle ':completion:*' max-errors 2 numeric zstyle ':completion:*' menu select=1 zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s ## Load colors autoload colors zsh/terminfo if [[ "$terminfo[colors]" -ge 8 ]]; then colors fi for color in RED GREEN YELLOW BLUE MAGENTA CYAN WHITE; do eval PR_B_$color='%{$terminfo[bold]$fg[${(L)color}]%}' eval PR_$color='%{$fg[${(L)color}]%}' (( count = $count + 1 )) done PR_NO_COLOR="%{$terminfo[sgr0]%}" PR_B='%{$terminfo[bold]%}' ## See if we can use extended characters to look nicer. typeset -A altchar set -A altchar ${(s..)terminfo[acsc]} PR_SET_CHARSET="%{$terminfo[enacs]%}" PR_SHIFT_IN="%{$terminfo[smacs]%}" PR_SHIFT_OUT="%{$terminfo[rmacs]%}" PR_HBAR=${altchar[q]:--} PR_ULCORNER=${altchar[l]:--} PR_LLCORNER=${altchar[m]:--} PR_LRCORNER=${altchar[j]:--} PR_URCORNER=${altchar[k]:--} PR_LEND=${altchar[u]:--} PR_REND=${altchar[t]:--} ## Make prompt ZSH_THEME_GIT_PROMPT_PREFIX="%{$reset_color%}%{$fg[green]%}[" ZSH_THEME_GIT_PROMPT_SUFFIX="]%{$reset_color%}" ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[red]%}*%{$reset_color%}" ZSH_THEME_GIT_PROMPT_CLEAN="" USER_INFO="" # If user is root => change prompt color for name and hostname if [ "$USERNAME" = "root" ]; then USER_INFO="%B%{$fg[red]%}%n%{$reset_color%}%B%{$fg[green]%}%B@%{$fg[red]%}" else USER_INFO="%B%{$fg[green]%}%n%{$reset_color%}%B%{$fg[red]%}%B@%{$fg[green]%}" fi local ret_status="%(?:%{$fg_bold[green]%}0:%{$fg_bold[red]%}%?)" # local BAR_COLOR="%(?:$PR_BLUE:$fg_bold[red])" local BAR_COLOR="$PR_BLUE" # Set git custom status var_git_custom_status='$(git_custom_status)' # Set docker custom status var_docker_custom_status='$(docker_custom_status)' # Set k8s custom status var_k8s_custom_status='$(k8s_custom_status)' # Set prompt PS1="$PR_B$BAR_COLOR$PR_SHIFT_IN$PR_ULCORNER\ $PR_HBAR$PR_HBAR$PR_HBAR$PR_LEND\ $PR_SHIFT_OUT${PR_B}\ [ %{$fg[yellow]%}METAL$BAR_COLOR${PR_B} ]\ ${ret_status} \ $BAR_COLOR${PR_B}\ [ $USER_INFO%M%{$reset_color%}%b:%B%{$fg[yellow]%}%~%{$reset_color%}${var_docker_custom_status}${var_git_custom_status}${var_k8s_custom_status}$BAR_COLOR${PR_B} ] $BAR_COLOR$PR_SHIFT_IN$PR_LLCORNER$PR_HBAR$PR_LEND\ $PR_SHIFT_OUT$PR_NO_COLOR " ## Kubernetes which kubectl > /dev/null if [ "$?" -eq 0 ] then export KUBECONFIG=/etc/kubernetes/admin.conf source <(kubectl completion zsh) fi ## Aliases curlFormat=" time_namelookup: %{time_namelookup}\n time_connect: %{time_connect}\n time_appconnect: %{time_appconnect}\n time_pretransfer: %{time_pretransfer}\n time_redirect: %{time_redirect}\n time_starttransfer: %{time_starttransfer}\n ----------\n time_total: %{time_total}\n" # Apt alias agu="apt update" alias agdu="apt dist-upgrade" alias agi='apt install' alias acs="apt-cache search" alias acp="apt-cache policy" # Git alias gc='git clone' alias gsi='git status --ignored' alias gad='git add' alias gcm='git commit -m' alias gpu='git push' alias gck='git checkout' alias gpr='git pull --rebase' # Docker alias dps='docker ps' alias dpsa='docker ps -a' alias dex='docker exec -it' alias dlt='docker logs -f --tail=1000' alias dtools='docker run -it --rm nurza/tools zsh' # Kubernetes alias k='kubectl' alias kl='kubectl logs -f --since 5m' alias kg='kubectl get' alias kaf='kubectl apply -f' alias kad='kubectl delete -f' alias kds='kubectl describe' alias kdl='kubectl delete' alias kcu='kubectl config use-context' alias kgpg='kg pods -o wide | grep --color=always -i' alias kgp='kg pods -o wide | awk '"'"'{print $1" "$2" "$3" "$4" "$5" "$6" "$7}'"'"' | column -t' alias kgpa='kg pods -o wide --all-namespaces' alias kgps='kg pods -o wide --sort-by="{.spec.nodeName}"' alias kgpas='kg pods -o wide --all-namespaces --sort-by="{.spec.nodeName}"' alias kexec='kubectl exec -it' # Pygmentize alias pjson='json|pygmentize -l json' alias pyaml='pygmentize -l yaml' alias pgo='pygmentize -l go' alias pshell='pygmentize -l shell' # Misc alias cpr='rsync -r --links --info=progress2' alias g='grep' alias grepc='grep --color=always' alias gc='grep --color=always' alias grepi='grep -i' alias gi='grep -i' alias grepci='grepi --color=always' alias gci='grepi --color=always' alias ds='dush .' alias l=' ls -lh --time-style="+%Y-%m-%d %H:%M%:::z" --color=always' alias ll=' ls -lh --time-style="+%Y-%m-%d %H:%M%:::z" --color=always' alias lla=' ls -lha --time-style="+%Y-%m-%d %H:%M%:::z" --color=always' alias llt=' ls -lht --time-style="+%Y-%m-%d %H:%M%:::z" --color=always' alias llat='ls -lhat --time-style="+%Y-%m-%d %H:%M%:::z" --color=always' alias untar='tar xf' alias del='rm -rf' alias search='find . | grep' alias searchi='find . | grep -i' alias xc='xclip -selection clipboard' alias rmhost="ssh-keygen -f '$HOME/.ssh/known_hosts' -R" alias json="python -m json.tool" alias simplehttpserver="python -m SimpleHTTPServer 8000" alias psgrep='ps aux|grep --color=always' alias psgrepi='ps aux|grep --color=always -i' alias netlist='netstat -laputen|grep LISTEN' alias curls="curl -w '$curlFormat' -o /dev/null -s" alias dfh='df -h' alias dfi='df -ih' alias dfc='dfc -dT -t -tmpfs,overlay,squashfs' alias htopf='htop -d 0.1' alias ping8='ping -O -i 0.2 8.8.8.8' alias datez='date +%Y-%m-%d_%H-%M%:::z' alias timez='date +%T.%3N' alias tailf='tail -f' alias fori='for i in' alias b64='base64 -w 0' alias b64d='base64 -d' # AWK alias awk1='awk "{print \$1}"' alias awk2='awk "{print \$2}"' alias awk3='awk "{print \$3}"' alias awk4='awk "{print \$4}"' alias awk5='awk "{print \$5}"' alias awk6='awk "{print \$6}"' alias awk7='awk "{print \$7}"' alias awk8='awk "{print \$8}"' alias awk9='awk "{print \$9}"' # Quick cd alias cdd='cd ..' alias cddd='cd ../..' alias cdddd='cd ../../..' alias cddddd='cd ../../../..' alias cdddddd='cd ../../../../..' alias cddddddd='cd ../../../../../..' alias cdddddddd='cd ../../../../../../..' alias cetc='cd /etc' alias ctmp='cd /tmp' alias cdocker='cd /var/lib/docker' alias cwww='cd /var/www' alias clog='cd /var/log' ## Misc bindkey \^U backward-kill-line ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern) setopt interactivecomments ## Source custome zshrc source ~/.zshrc.custom &> /dev/null