Bash Beispiele ============== ( !!! Greg's Wiki !!! http://mywiki.wooledge.org/ ) ( for robust scripts see http://www.davidpashley.com/articles/writing-robust-shell-scripts/ ) ( Grundlagen für Bash-Scripting: see https://wiki.ubuntuusers.de/Shell/Bash-Skripting-Guide_f%C3%BCr_Anf%C3%A4nger/#Die-Shebang ) 1.) allg ======== --- alias cdb='cd ~kofler/linuxbuch' alias more=less --- echo $0 # (gibt aktuelle Shell aus) # Interpretation von wenigen Sonderzeichen: $ \ ` echo "Das ist der Zugriffspfad: $PATH" echo 'Das ist der Zugriffspfad: $PATH' # keine Interpretation rm 'ab* $cd' rm ab* \$cd --- ls | tee inhalt kommando > datei kommando < datei kommando 2> datei # (Fehler) kommando >& datei # (Ausgabe + Fehler) kommando &> datei # (Ausgabe + Fehler) kommando >> datei Von den beiden Zeilen programm 2>&1 >file und programm >file 2>&1 ist die zweite Version vorzuziehen, da die erste Kommandozeile stderr auf den alte stdout setzt, und erst anschließend stdout auf filename umlenkt; stderr wird also i.d.R. nicht nach filename umgelenkt werden. e.g. Umleitung auf STDOUT mit 2>&1 ffmpeg -i ./Als\ die\ Römer\ frech\ geworden.failed-conv.flv 2>&1 | grep -i audio --- find / -name '*sh' > ergebnis & ls # find Hintergrund, ls Vordergrund [1] 334 # (Rückgabewert) # Nr Hintergrundprozess der Shell, PID (ls; date) > inhalt kommando1 && kommando2 # (wenn Rückgabe 0 = fehlerfrei, wird 2 ausgeführt) kommando1 || kommando2 # (wenn Rückgabe 1 = fehler, wird 2 ausgeführt) --- echo $[2+3] --- VAR-Name: [A..Z,a..z,0..9,_] var=abc echo $var echo ${var} echo ${!var*} https://stackoverflow.com/questions/8515411/what-is-indirect-expansion-what-does-var-mean var='abc def' a=$a'xxx'$a PATH=$PATH':~/bin' a=3; let a=3; declare a=3 export a export a=3 declare -x a=3 local a=3 export; printenv set unset a --- ls -lisad .[!.]* echo /* echo /[a-f]* echo {a,b,c}{d,e,f}.{1,2,3} # -> ae.1 ae.2 ae.3 af.1 af.2 ..... a=$[$a*4] echo $a echo ${!n} the value of the variable whose name is in this variable $(…) runs the command specified inside the parentheses in a subshell 2.) Bash-Programmierung ======================= # sucht Dateien, die best. String enthalten: find -type f -exec grep -q $1 {} \; -print # ohne start einer subshell ein shell-script starten: . addpwd # hier definierte Variablen werden übernommen --- read a echo $a a.) vordef. Variable ==================== $? Rückgabewert ( = 0 -> ok, != 0 -> err ) (Var. wird nach neuem Befehl neu beschrieben, vorher Wert sichern !) $# Zahl der übergeb. Params $0 -sh bzw. scriptname $1 bis $9 Param 1 .. 9 $* oder $@ alle übergeb. Params ($!) Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin. (https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#Special-Parameters) b.) Param-Substitution ====================== Verwenden der Variablenersetzung Variablenersetzungen wenden beginnend von links oder rechts ein Schema auf den Inhalt einer Variablen an. Die folgende Liste enthält die möglichen Syntaxformen: ${VAR#schema} entfernt die kürzeste mögliche Übereinstimmung von links: file=/home/tux/book/book.tar.bz2 echo ${file#*/} home/tux/book/book.tar.bz2 ${VAR##schema} entfernt die längste mögliche Übereinstimmung von links: file=/home/tux/book/book.tar.bz2 echo ${file##*/} book.tar.bz2 ${VAR%schema} entfernt die kürzeste mögliche Übereinstimmung von rechts: file=/home/tux/book/book.tar.bz2 echo ${file%.*} /home/tux/book/book.tar ${VAR%%schema} entfernt die längste mögliche Übereinstimmung von rechts: file=/home/tux/book/book.tar.bz2 echo ${file%%.*} /home/tux/book/book c.) Verzweigungen ================= if test $# -ne 2; then echo "falsche ... Zahl" exit 1 else echo "P1 $1, P2 $2" fi if ! test -d /media/sdb2/SIK/SIK-Android/DATA/bkup-01; then mkdir /media/sdb2/SIK/SIK-Android/DATA/bkup-01; fi for i in a b c; do echo $i; done for i in *.tex; do cp $i $i~; done for datei in $(ls *.txt); do echo "Datei: $datei" done while IFS= read -r zeile; do echo "Zeile: $zeile" done < meine_datei.txt dir_names="aa bb cc" for i in $dir_names; do echo $i; done # if space in DIR-name src do to get all file-names in DIR src: for i in "${src}"* ; do echo \"${i}\" ; done i=1; while [ $i -le 5 ]; do echo $i; i=$[$i+1]; done i=1; until [ $i -gt 5 ]; do echo $i; i=$[$i+1]; done break Verlassen der for/while/until Schleife continue sofortiges Starten eines neuen for/while/until Schleifen-Durchgangs d.) Test ======== ( for more test-options run: bash -c "help test" ) [ -f /etc/shadow ] && echo "This PC uses shadow passwords" [ -d /etc/apt ] && echo "Directory \"/etc/apt\" exists" if test -e /etc/apt ; then echo "file/directory \"/etc/apt\" exists (2)" else echo "file/directory /etc/apt does not exist" fi oder auch: if test ! -e /etc/apt ; then usw. if test "$owner" = "$vdr" ; then z.B. Ausdruecke: arith: n1 -eq n2; n1 -ne n2; n1 -gt n2; n1 -ge n2; n1 -lt n2; n1 -le n2; string: -z $1; zkt1 = zkt2; zkt1 != zkt2; ... # !!! space before and after operator important !!!, string may be surrounded by double quotes use "man test" for getting infos about bash test EXPR1 -a EXPR2 True if both expr1 AND expr2 are true. EXPR1 -o EXPR2 True if either expr1 OR expr2 is true. if test -f /foo1 -a -f /foo2 ; then .... e.) Arithmetik ============== long Darstellung ohne Overflow-Pruefung 067, 0x1a Operatoren -,+; !,~; */%; +,-; +,-; <<,>>; <=,>=,<,>; ==,!=; &,^|; &&,||; =,*=,/=,%=,+=, ..... Auswertung: $[ausdruck], $((ausdruck)), let ausdruck ... z.B. echo $((10+$[4+5*6])) f.) Ausgabe eines Kommandos als Parameter ========================================= rm -f `find . -name \*.orig` rm -f $(find . -name \*.orig) dev-name=`blkid -U "5032-6789"` g.) Funktion function abc () { echo 1 2 3 [; return] } ( Aufruf: abc donar, use var in func as $i (== donar) BEISPIELE see ~/lib/Shell-Scripts/menu/utilitymenu.sh h.) Array ## declare an array variable declare -a arr=("element1" "element2" "element3") # now loop through the above array for i in "${arr[@]}" do echo "$i" # or do whatever with individual element of the array done # You can access them using echo "${arr[0]}", "${arr[1]}" # Also works for multi-line array declaration declare -a arr=("element1" "element2" "element3" "element4" )