Tipps für Bash Skripte

1. Startzeile eines Bash-Skripts:

#!/bin/bash
echo "Hello world!"
top

1.1. Textausgaben:

echo . 9 "Hello World"" and Good Bye"

helloWorld="Hello World"
echo "1: $helloWorld"
echo "2: ${helloWorld}abc"
echo "3:\n$helloWorld"
echo -e "4:\n$helloWorld"
echo '5: $helloWorld'
Output:
. 9 Hello World and Good Bye
1: Hello World
2: Hello Worldabc
3:\nHello World
4:
Hello World
5: $helloWorld
top

1.2. Sourcecode in Skript einbinden:

. ./tmp/andereBashSkriptDatei
# oder auch:
source ./tmp/andereBashSkriptDatei
top

1.3. Textmanipulationen:

text="ABC123ABC456ABC"

# Substring up to end
text1=${text:position}

# Substring with length
text2=${text:position:length}

# Replace only at beginning
text3=${text/#suchen/ersetzen}

# Replace only at end
text4=${text/%suchen/ersetzen}

# Replace first occurence
text5=${text/ABC/DEF}

# Replace every occurence
text6=${text//suchen/ersetzen}

# Remove shortest patternmatch at beginning
text7=${textorg#pattern}

# Remove shortest patternmatch at end
text8=${textorg%pattern}

# Remove longest patternmatch at beginning
text9=${textorg##pattern}

# Remove longest patternmatch at end
text10=${textorg%%pattern}

# Patternparts:
#  * wildcard
top

2. Möglichkeiten von Funktionsaufrufen:

function echoText {
  echo "Text1"
}

function returnVariable {
  echo $1
}

function add {
  local returnValue=$(($1 + $2))
  echo ${returnValue}
}

echoText
echo $(echoText)
echo $(returnVariable "Text2")
add 1 2
echo $(add 1 2)
result=$(add 1 2)
echo ${result}
Output:
Text1
Text1
Text2
3
3
3
top

3. Verzweigungen und Schleifen:

3.1. If-Anweisung:

variable=1
if [ ${variable} = 1 ]; then {
  echo "If case 1"
} fi

if [ ${variable} = 0 ]; then {
  echo "If case 2"
} else {
  echo "Else case 2"
} fi

if [ ${variable} = 0 ]; then {
  echo "If case 3"
} elif [ ${variable} = 1 ]; then {
  echo "Else if case 3"
} else {
  echo "Else case 3"
} fi

variable2="abc"
if [ ${variable2} = "abc" ]; then {
  echo "variable2=abc"
} fi

if [ ! "${variable2}" = "xyz" ]; then {
  echo "!variable2=xyz"
} fi

if [ "${variable2}" != "xyz" ]; then {
  echo "variable2!=xyz"
} fi

if [ ${variable2} = "abc" ]
  then
    echo "if-variant1"
fi

if [ ${variable2} = "abc" ]; then echo "if-variant2"; fi

if [[ ${variable2} == a* ]]; then {
  echo "if-variant3"
} fi

if test ${variable} -gt 0
  then
    echo "if-variant4"
fi

test ${variable} -gt 0 && echo "if-variant5"
Output:
If case 1
Else case 2
Else if case 3
variable2=abc
!variable2=xyz
variable2!=xyz
if-variant1
if-variant2
if-variant3
if-variant4
if-variant5
top

3.2. Test-Tool:

http://wiki.bash-hackers.org/commands/classictest
top

3.3. While-Anweisung:

i=1
limit=4
while [ $i -lt $limit ]
do
  echo $i
  i=$[$i + 1]
done

i=4
while [ $i -lt 7 ]; do
  echo $i
  i=$[$i + 1]
done

for i in 7 8 9; do
  echo $i
done

for i in {10..12}
do
  echo $i
done
Output:
1
2
3
4
5
6
7
8
9
10
11
12
top

4. Ermitteln der Länge eines Strings:

testVariable="Hello world!"
textLength=${#testVariable}
echo ${textLength}
top

4.1. Trim eines Strings:

function trim {
  local var=$1
  # remove leading whitespace characters
  var="${var#"${var%%[![:space:]]*}"}"
  # remove trailing whitespace characters
  var="${var%"${var##*[![:space:]]}"}"
  echo -n "$var"
}

variable="  abc  "
echo $(trim ${variable})
top

5. Ermitteln der aktuellen Zeit:

now=`date +%Y%m%d_%H%M%S`
echo ${now}
top

6. Ermitteln eines Variablenwertes anhand des Variablennames in einer anderen Variablen:

textVariable="Content"
variableName="textVariable"
echo ${!variableName}
top

7. Ändern der Farbe für Bildschirmausgaben:

# set text output to red
tput setaf 1

echo "Red text"

# reset text color
tput sgr0
top

7.. Text in Farbe ausgeben:

echo -e "\033[4;31mText in rot und unterstrichen\033[0m"
echo -e "\e[4;31mText in rot und unterstrichen\e[0m"

  alle Attribute zurücksetzen
  Fettschrift
  Unterstreichen
  Blinken (ohne Funktion via ssh)
  inverse Darstellung
  Schriftfarbe schwarz
  Schriftfarbe rot
  Schriftfarbe grün
  Schriftfarbe gelb
  Schriftfarbe blau
  Schriftfarbe magenta
  Schriftfarbe türkis
  Schriftfarbe weiß
  Hintergrund schwarz
  Hintergrund rot
  Hintergrund grün
  Hintergrund gelb
  Hintergrund blau
  Hintergrund magenta
  Hintergrund türkis
  Hintergrund weiß
top

7.2. Echo Ausgabeparameter:

echo -n "Text ohne Zeilenumbruch"
echo -e "\\ backslash"
echo -e "\a alert (BEL)"
echo -e "\b backspace"
echo -e "\c produce no further output"
echo -e "\e escape"
echo -e "\f form feed"
echo -e "\n new line"
echo -e "\r carriage return"
echo -e "\t horizontal tab"
echo -e "\v vertical tab"
top

8. Umwandeln eines Variableninhaltes in Lower-Case:

testVariable=TrUe
lowerCase=${testVariable,,}
echo ${lowerCase}
top

9. Ausgabe eines Textes mit einer Umrahmung:

# echoBoxed (text, boxChar = *)
function echoBoxed {
  local boxChar=$2
  if [ "${boxChar}" == "" ]; then {
    local boxChar=*
  } fi
  
  local textLength=${#1}
  local textLength=$((${textLength} + 4))
  
  for i in $(seq 1 ${textLength}); do printf "%s" "${boxChar}"; done
  echo ""
  
  printf "%s" "${boxChar} $1 ${boxChar}"
  echo ""
    
  for i in $(seq 1 ${textLength}); do printf "%s" "${boxChar}"; done
  echo ""
}

echoBoxed "Text in a box"
top

10. Auslesen von Werten aus Property-Dateien:

# getPropertyValue (propertyName, properties_file = ... .properties)
# default properties_file is the bash-script filename without .sh extended with .properties
function getPropertyValue {
  local properties_file=$2
  if [ "${properties_file}" == "" ]; then {
    properties_file=${0/.sh/}.properties
  } fi
  local value=`sed '/^\#/d' ${properties_file} | grep "^ *$1 *=" | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
  echo ${value}
}

echo $(getPropertyValue submarker.propvalue)
top

11. Löschen von veralteten Dateien in einem Verzeichnis:

outdateDays=20
checkDirectory=/tmp
if [ ${outdateDays} -gt 0 -a "${checkDirectory}" != "" -a "${checkDirectory}" != "/" ]; then {
  find ${checkDirectory}/* -maxdepth 0 -type d -ctime +${outdateDays} -exec rm -rf '{}' \;
} fi
top

12. Interaktive Auswahl eines Wertes:

selectableItems="Item_1 Item_2 Item_3"
quitText="Abort / Exit / Quit"
select selectedItem in ${selectableItems} "${quitText}"
do
  if [ "${selectedItem}" == "${quitText}" ]; then {
    exit 1
  } else {
    break;
  } fi
done

echo ${selectedItem}
top

13. Auslesen und Speichern eines Voreinstellungswertes:

lastValue=
if [ -f ~/.preferenceFile ]; then {
  lastValue=`cat ~/.preferenceFile`
} fi

while [ true ]
do
  read -p "Enter value (default=${lastValue}): " nextValue
  case "${nextValue}" in
    "" ) value=${lastValue}; break;;
    [0-9]* ) value=${nextValue}; break;;
    abc ) value=${nextValue}; break;;
    * ) echo "Invalid value (must be 'abc' or numeric";;
  esac
done
echo "${value}"> ~/.preferenceFile

echo "value: ${value}"
top

14. Aufruf einer Internetseite:

batchcmd="http://hostname:port/etc/pp"
countlines=`wget --quiet $batchcmd -O - | grep "GesuchterInhaltDerErfolgAnzeigt" | wc -l`
if [ $countlines = 1 ];
then
  echo "Batchaufruf erfolgreich ausgefuehrt"
  exit 0
else
  echo "Fehler beim Batchaufruf!" >&2
  exit 1
fi
top

15. Nutzung eines selbst definierten Trennzeichens für Listen:

itemList=Item_1,Item_2,Item_3
IFS=$','
for item in ${itemList}
do
  echo ${item}
done
unset IFS
top