Skip to main content

bash

Arbeiten mit Variablen

Arrays

Array erstellen

 # Array mit virtuellen Maschinen anlegen
 machines=(vm01,vm02,vm03)
 # Erstellt eine Liste mit den virtuellen Maschinen
    IFS=';' read -r -a arrhosts <<< $(echo $machines | tr ',' ';')

Array iterieren

    echo "Hier eine Liste der virtuellen Maschinen : "
    i=0
    for vm in "${arrhosts[@]}"
    do 
        echo $i" - "$vm
	i=$(($i+1))
    done
    
    #Ausgabe:
    0 - vm01
    2 - vm02
    3 - vm03

Scripte mit Parametern

 

Beispiel mit Abfrage eines bestimmten Wertes der Parametern

https://stackoverflow.com/a/16496491

#!/bin/bash

usage() { echo "Usage: $0 [-s <45|90>] [-p <string>]" 1>&2; exit 1; }

while getopts ":s:p:" o; do
    case "${o}" in
        s)
            s=${OPTARG}
            ((s == 45 || s == 90)) || usage
            ;;
        p)
            p=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${s}" ] || [ -z "${p}" ]; then
    usage
fi

echo "s = ${s}"
echo "p = ${p}"

Ausgabe:

$ ./myscript.sh
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -h
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s "" -p ""
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 10 -p foo
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 45 -p foo
s = 45
p = foo

$ ./myscript.sh -s 90 -p bar
s = 90
p = bar

Beispiel mit getopts

http://mywiki.wooledge.org/BashFAQ/035

!/bin/sh
# Usage info
show_help() {
cat << EOF
Usage: ${0##*/} [-hv] [-f OUTFILE] [FILE]...
Do stuff with FILE and write the result to standard output. With no FILE
or when FILE is -, read standard input.

-h          display this help and exit
-f OUTFILE  write the result to OUTFILE instead of standard output.
-v          verbose mode. Can be used multiple times for increased
                verbosity.
EOF
}

# Initialize our own variables:
output_file=""
verbose=0

OPTIND=1
# Resetting OPTIND is necessary if getopts was used previously in the script.
# It is a good idea to make OPTIND local if you process options in a function.

while getopts hvf: opt; do
    case $opt in
        h)
              show_help
              exit 0
              ;;
          v)  verbose=$((verbose+1))
              ;;
          f)  output_file=$OPTARG
              ;;
          *)
              show_help >&2
              exit 1
              ;;
      esac
done
shift "$((OPTIND-1))"   # Discard the options and sentinel --

# Everything that's left in "$@" is a non-option.  In our case, a FILE to process.
printf 'verbose=<%d>\noutput_file=<%s>\nLeftovers:\n' "$verbose" "$output_file"
printf '<%s>\n' "$@"

# End of file