Bash | Cookbook

Inhaltsverzeichnis

Configure Bash Environment

Using Bash Completion

Add git completion

Download git-completion.bash to $HOME/etc

$ mkdir $HOME/etc
$ cd $HOME/etc
$ wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash

Add git-prompt to .bashrc

. $HOME/etc/git-completion.sh

Add completion for Makefiles

Add this to .bashrc

complete -W "`grep -oE '^[a-zA-Z0-9_.-]+:([^=]|$)' ?akefile | sed 's/[^a-zA-Z0-9_.-]*$//'`" make

Customize Bash prompt

Add git repository/branch to prompt

Download git-prompt.sh to $HOME/etc

$ mkdir -p $HOME/etc
$ cd $HOME/etc
$ wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

Add git-prompt to .bashrc

. $HOME/etc/git-prompt.sh

Configure prompt to display git branch

export PS1='[\033[33;1m]\w[\033[m] [\033[32m]$(__git_ps1 " 



Writing Bash Scripts

Set vi commands in bash-script

Parsing Parameter

$ brew install gnu-getopt

Bash Script Template

#------------------------------------------------------------------------------------------
CMD_GETOPT=/usr/local/opt/gnu-getopt/bin/getopt

S_OPTS="vdm:"
L_OPTS="verbose,debug,versions,install:,init:"

OPTS=$($CMD_GETOPT --options "$S_OPTS"--longoptions "$L_OPTS"    -- "$@")

eval set $OPTS
shift

while [[ $# -gt 0 ]]; do
    echo "Param 1: '$1'"

    case "$1" in
        -v | --verbose)    VERBOSE=true;                 ;;
        -d | --debug)      DEBUGLEVEL="$2";  shift       ;;

        --versions)        MODE=GETVERSIONS              ;;
        --install)         TYPE="$2";        shift
                           MODE=INSTALL                  ;;

        --init)            MODE=INIT                     ;;

        --)                                  shift; break;;
        * )                                         break;;
    esac

    shift
done

Show progress with a spinner

#!/bin/bash
 
COMMAND="${1^^}"
 
SYMBOL_PASS="$(printf '\e[0;32m\xe2\x9c\x94\e[0m')"
SPINNER_STATE='\|/-'
 
spinner()
{
        local _lastpos=$((${#SPINNER_STATE}-1))
        SPINNER_STATE="${SPINNER_STATE:$_lastpos:1}${SPINNER_STATE:0:$_lastpos}"
 
        printf 
}
 
#---------------------------------------------------------------------------------------------------
#
#---------------------------------------------------------------------------------------------------
if [[ "$COMMAND" = "STEP1" ]]; then
        printf 
        _LASTDATE=
        for _LINE in *.csv
        do
                _FILE="$(basename $_LINE)"
                _CURRDATE=${_FILE:19:8}
                rm    -rf       $_CURRDATE
                mkdir -p        $_CURRDATE
                cp       $_LINE $_CURRDATE
 
                if [[ "$_CURRDATE" = "$_LASTDATE" ]]; then
                        spinner
                else
                        printf "${SYMBOL_PASS}\n${_CURRDATE}: "
                fi
 
                _LASTDATE=$_CURRDATE
        done
        printf "\n"
fi