bash - ein LinuX-Kommandointerpreter

Auf dieser Seite arbeite ich an einer Beschreibung der bash. Sie ist in Anlehnung an die man-page entstanden und immer noch in Arbeit. Wann immer ich Zeit dazu habe, werden ich die Texte vervollständigen, erweitern und korrigieren. Ich kann mich natürlich nicht für die Vollständigkeit und Richtigkeit aller Beschreibungen verbürgen, da einem natürlich unweigerlich Fehler unterlaufen. Für Hinweise zu Fehlern, Ergänzungen und Lob bin ich jederzeit dankbar.

Der Begriff "Kommandointerpreter" wird der Sache vielleicht nicht ganz gerecht, denn die bash bietet neben der Möglichkeit Kommandos/Programm zu starten durch eine Reihe sehr mächtiger internen Kommandos und Funktionalitäten eine große Vielfalt von Einsatzmöglichkeiten. Nicht zuletzt ist eine möglichst genaue Kenntnis der Shell eine Grundvoraussetzung, um erfolgreich eigene Shell-Scripte zu schreiben.

  1. Inhalt

    1. Inhalt
    2. Einleitung
    3. Aufruf der bash
    4. Definitionen
    5. Reservierte Worte
    6. einfacher Kommandoaufruf
    7. Pipelines
    8. Listen
    9. komplexe Kommandos
    10. Kommentare
    11. Quoting
    12. Parameter
    13. shell-Variablen
    14. Arrays
    15. Expansion
    16. Pattern Matching
    17. Quote Removal
    18. Umleitung von Datenströmen (Redirection)
    19. Aliases
    20. Functions
    21. Arithmetische Berechnungen
    22. Vergleichsoperationen
    23. Simple Command Expansion
    24. Command Execution
    25. Command Execution Environment
    26. Environment
    27. Exit Status
    28. Signale
    29. Job Control
    30. Prompting
    31. Readline
    32. History
    33. History Expansion
    34. Interne Shell Kommandos (Shell Builtin Commands)
    35. Restricted Shell
    36. Files
  2. Einleitung

    Die bash ist einer der vielen Kommandointerpreter von LinuX. Sie ist shell (sh) kompatibel und auf vielen Systemen ist sh ein Link auf die bash. Die bash liest Kommandos von STDIN oder einem File und führt diese aus. Mit verschiedenen Optionen beim Start der bash wird ihr Verhalten grundsätzlich beeinflusst.

  3. Aufruf der bash

    Je nachdem, wie die bash gestartet wird, ist ihr Verhalten unterschiedlich.

    • login-shell

      Wird die bash als interaktive login-shell gestartet, so testet sie zuerst, ob das File /etc/profile existiert. Sollte das der Fall sein, so wird es eingelesen und entsprechend ausgeführt. Danach testet die bash, ob im Homeverzeichnis des Users die Dateien .bash_profile, .bash_login und .profile existieren. Die erste dieser Dateien, die gefunden wird und lesbar ist, wird durch die bash eingelesen und ausgeführt. Alle folgenden Dateien werden nicht berücksichtigt. So wird z.B. der Inhalt der Datei .profile durch die login-shell nicht berücksichtigt, wenn gleichzeitig eine lesbare Datei .bash_profile im Homeverzeichnis angelegt ist. Dieses Verhalten kann mit der bash-Option --noprofile abgeschaltet werden.

    • interaktive shell

      Wenn die bash als interaktive nicht-login-shell gestartet wird, dann liest sie zuerst die Datei .bashrc aus dem Homeverzeichnis und führt sie aus, wenn sie existiert und lesbar ist. Mit der bash-Option --norc kann dieses Verhalten abgeschaltet werden. Mit der bash-Option --rcfile dateiname kann die bash veranlasst werden statt dessen die Datei dateiname einzulesen und auszuführen.

    • nicht interaktive shell

      Wenn die bash als nicht-interaktive shell gestartet wird, so liest sie die Variable $BASH_ENV ein, expandiert die Werte und führt sie dann aus.

    • /bin/sh

      Wird die bash als /bin/sh aufgerufen, so berücksichtigt sie nur die Dateien /etc/profile und die Datei .profile im Homeverzeichnis.

    • remote-shell

      Wird die bash als remote-shell (r-kommandos) aufgerufen, so liest sie nur die Datei .bashrc ein und führt sie aus.

  4. Definitionen

    blank
    Leerzeichen space und Tabulator tab
    word
    Folge von Zeichen a-z A-Z
    name
    Folge von Zeichen a-z, A-Z, 0-9 und _, wobei das erste Zeichen keine Zahl sein darf
    metacharacter
    Wenn diese Zeichen nicht gequotet sind, wirken sie als Trennzeichen ¦ & ; ( ) < > space tab
    control operator
    Die Zeichenfolgen ¦ ¦¦ & && ; ;; ( ) <newline>
  5. Reservierte Worte

    Die reservierten Worte haben innerhalb der bash eine besondere Bedeutung und dürfen nicht frei verwendet werden, da sie besondere Funktionalitäten besitzen oder interne Kommandos auslösen. Diese Worte sind ! case do done elif else esac fi for function if in select then until while { } time [[ ]].

  6. Einfache Kommandoaufrufe

    Einfache Kommandoaufrufe in der shell bestehen aus einer Abfolge von Zeichen, die gebildet werden aus dem Kommandonamen selbst und einer Reihe von optionalen Optionen und Parametern, die durch blanks voneinander getrennt sind. Den Abschluss bildet ein control-operator. Der Rückgabewert des Kommandos ist der entsprechende exit-status des Kommandos, oder ein Wert 128+n, wenn das Kommando durch das Signal n unterbrochen wurde.
    command [optionen] [parameter]

  7. Pipelines pipe

    Eine Pipeline ist eine Abfolge von einfachen Kommandos, die durch das Zeichen ¦ (Pipe) voneinander getrennt sind.
    Beispiel:
    Kommando1 ¦ Kommando2
    oder
    Kommando1 ¦ Komando2 ¦ Kommando3 ¦ .......
    Der Standard-Output von Kommando1 wird dabei an den Standard-Input von Kommando2 weiter geleitet, usw. Diese Verbindung wird hergestellt, noch bevor andere Umleitungen durch die bash vorgenommen werden. Die bash wartet, bis die Ausführung des letzten Kommandos der Pipeline abgeschlossen wurde und gibt dann den exit-status des letzten Kommandos zurück. Jedes Kommando der Pipeline wird in einem separaten Subshell-Prozess ausgeführt.

  8. Listen list

    Eine Liste ist eine Abfolge von einer oder mehrerer Pipelines, die durch die Operatoren ; & && oder ¦¦ voneinander getrennt und mit ; & oder <newline> abgeschlossen werden. Innerhalb der Liste haben die Operatoren && und ¦¦ haben den gleichen Rang. Die Terminatoren ; und & besitzen ebenfalls einen gleichen, niederen Rang.
    Sollen innerhalb einer Liste mehere Kommandos nacheinander ausgeführt werden, so sind sie durch ein Semikolon voneinander zu trennen. Also
    Kommando1; Kommando2; ...
    Wenn ein Kommando mit dem control operator & beendet wird, so wird es in einer Subshell im Hintergrund ausgeführt. Die bash wartet dann nicht auf die Beendigung des Kommandos und gibt den return-code 0 zurück. Wenn die Kommandos mit dem control operator ; beendet werden, so werden die Kommandos nacheinander ausgeführt und die bash wartet, bis ein Kommando beendet ist, bevor das nächste aus der Liste startet. Der exit-code der Liste entspricht dem exit-code des letzten Kommandos. Die control operatoren && und ¦¦ erzeugen eine logische Verknüpfung der Listenelemente. In der AND-Form:
    Kommando1 && Kommando2
    wird Kommando2 nur dann ausgeführt, wenn Kommando1 vorher mit dem exit-status 0 (Null) beendet wurde. In der OR-Form:
    Kommando1 ¦¦ Komando2
    wird Kommando2 nur ausgeführt, wenn Kommando1 mit einem exit-status ungleich 0 (Null) beendet wurde.

  9. komplexe Kommandos

    • (liste)

      Die Liste wird in einer Subshell ausgeführt. Alle innerhalb der Subshell erzeugten Variablen haben nur auf diese Subshell selbst, oder eventuell von ihr erzeugte Subsubshells einen Effekt. Nach abarbeiten der Liste und beenden der Subshell geht ihr Inhalt verloren.

    • { liste; }

      Die Listen wird in der Shell ausgeführt. Die geschweifte Klammer dient der Gruppierung von Listen. Sie muss mit einem Semikolon oder <newline> abgeschlossen werden. Der exit-status ist der exit-status der Liste. Zu beachten ist, dass es sich bei den Klammern {} im Gegensatz zu () um reservierte Worte handelt, die durch die bash auch als solche erkannt werden müssen, deshalb sind sie von der Liste liste durch Leerzeichen oder Tabulatoren zu trennen.

    • ((expression))

      Die expression wird als arithmetischer Ausdruck interpretiert und in der selben Weise wie im Kommando let wird der Wert berechnet. Wenn das Ergebnis der Berechnung nicht Null ist, so wird der exit-status 0 (Null, wahr) zurückgegeben. Ansonsten ist der exit-status 1 (false). Eine Übersicht der verfügbaren Operatoren ist im Abschnitt Arithmetische Ausdrücke zu finden.

    • [[expression]]

      Die expression wird als Vergleichsausdruck interpretiert. Das Ergebnis des Vergleichs kann die Werte 0 (Null, wahr) oder 1 (falsch) annehmen. Eine Übersicht zu den Vergleichsoperatoren ist im Abschnitt Vergleichsoperatoren nachzulesen. Auf die expression wird die Tilde-Substitution, die Parameter- und Variablen-Expansion, die Arithmetik-Expansion, Kommando-Substitution und die Prozess-Substitution ausgeführt. Außerdem werden noch die Quotings entfernt. Auf expression wird kein "Word splitting" und keine Pfadnamen-Expansion angewendet. Bedingungen können mit den folgenden Operatoren kombiniert werden. Die Liste ist nach absteigender Rangfolge der Operatoren geordnet.

      • ( expression )
        Der Rückgabewert ist der Rückgabewert der Bedingung. Die Klammer wird benutzt, um die Rangfolge der Bedingung anzuheben und damit mehrere Bedingungen untereinander zu gruppieren.
      • ! expression
        NICHT-Verknüpfung. Der Rückgabewert der Bedingung wird negiert. Aus wahr wird falsch und aus falsch wird wahr.
      • expression1 && expression2
        UND-Verknüpfung. Der Rüchgabewert ist wahr, wenn beide Bedingungen wahr sind.
      • expression1 ¦¦ expression2
        ODER-Verknüpfung. Der Rückgabewert ist wahr, wenn mindestens eine der beiden Bedingungen wahr ist.

      ACHTUNG!!!! Die Operatoren && und ¦¦ testen die Bedingung expression2 nicht, wenn nach dem Test der Bedingung1 der Wahrheitswert der gesamten Bedingung schon fest steht.

    • for name [ in word ] ; do list ; done

      Mit diesem Konstrukt wird eine Zählschleife realisiert. Zuerst wird die Liste der Einträge word expandiert und erzeugt eine Liste von Werten. Diese müssen durch Leerzeichen getrennt sein. Bei jedem Schleifendurchlauf wird die Variable name mit dem nächsten Wert aus der Liste geladen und dann wird list ausgefürt. Der Rückgabewert entspricht dem exit-status des letzten Kommandos das ausgeführt wurde. Ergibt die Expansion der Liste hinter in eine leere Liste, so wird list nicht ausgeführt und der exit-status 0 zurückgegeben.

    • for (( expr1 ; expr2 ; expr3 )) ; do list ; done

      Mit diesem Konstrukt wird eine Zählschleife realisiert. Zuerst wird die Bedingung expr1 getestet. Wenn der Rückgabewert 0 (Null, zero, wahr) ist, wird die Bedingung expr2 getestet. Jedesmal, wenn die Bedingung expr2 den Rückgabewert >0 (nicht Null, non-zero, false) erzeugt, wird list ausgeführt und danach Bedingung expr3 getestet. Ansonsten wird die Schleife verlassen. Der Rückgabewert ist der exit-status der letzten Kommandos, das ausgeführt wurde.

      If any expression is omitted, it behaves as if it evaluates to 1.
    • select name [ in word ] ; do list ; done

      Zuerst wird die Liste der Einträge word hinter in expandiert und erzeugt eine Liste von Einträgen. Diese Liste wird nach STDERR ausgegeben, wobei jeder Eintag der Liste zusammen mit einer Nummer in einer Zeile ausgegeben wird. Abschließend erscheint der PS3-Prompt und es wird eine Zeile von STDIN gelesen. Stimmt der eingelesene Wert mit einer der Nummern überein, dann wird die Variable name mit dem entsprechenden word geladen und list ausgeführt. Wurde nur eine Leerzeile von STDIN gelesen, so wird die Liste erneut auf STDERR ausgegeben und eine Zeile von STDIN gelesen. Wenn ein EOF (<Strg>+d) gelesen wird, so wird die Schleife sofort verlassen. Jeder andere von STDIN gelesene Wert läd die Variable name mit einem Nullstring und führt die liste aus. Die gelesenen Daten sind in der shell-Variable REPLY lesbar. Durch das Kommando break innerhalb der liste kann die Schleife ebenfalls beendet werden. Der exit-status des select Kommandos ist der exit-status des letzten Kommandos, das in liste ausgeführt wurde.

    • case word in [ [(] pattern [ ¦ pattern ] .... ) list ;; ] ... esac

      Als erstes wird word expandiert und dann mit den einzelnen pattern verglichen. Es gelten dabei die selben Regeln wie bei der Pfadnamen-Expansion. Bei einer Übereinstimmung wird die zugehörige liste ausgeführt. Danach wird die case-Anweisung verlassen, es wird nicht auf eine weitere Übereinstimmung getestet. Der exit-status der case-Anweisung entspricht dem exit-status des letzten ausgeführten Listenkommandos.

    • if list1; then list2; [ elif list3; then list4; ] ... [ else list; ] fi

      Mit diesem Konstukt kann eine bedingte Ausführung von Listen erzeugt werden. Dabei funktioniert if ähnlich wie in anderen Programmiersprachen auch. Der gesamte Block wird durch if .... fi geklammert.
      Die Liste list1 wird ausgeführt und wenn diese einen exit-status 0 (Null) zurückgibt, dann wird die Liste list2 ausgeführt. Wenn der exit-status der Liste list1 nicht Null sein sollte, so wird die Liste list2 nicht ausgeführt. Danach wird der Test auf weitere elif-Statements durchgeführt. Sollte also Liste list3 den exit-status Null zurückliefern, dann wird die Liste list4 ausgeführt usw, usf. Ansonsten wird als Alternative Liste list5 nach der else-Anweisung ausgeführt. Der exit-status entspricht dem exit-status des letzten ausgeführten Kommandos. Eine Schachtelung von mehreren if-Blöcken ist möglich.

    • while list1; do list2; done
      until list1; do list2; done

      Das while-Kommando testet den exit-status der Liste list1. Wenn der exit-status 0 (Null, wahr) ist, wird die Liste list2 ausgeführt. Wenn der exit-status nicht Null ist, so wird die while-Schleife verlassen. Das until-Kommando ist das genaue Gegenteil. Das Kommando list2 wird solange ausgeführt, wie list1 einen exit-status ungleich Null zurückliefert. Wenn der exit-status 0 (Null, wahr) ist, wird die until-Schleife verlassen. Der exit-status der while und until-Schleife entspricht dem exit-status des letzten ausgeführten Kommandos der Listen.

    • [ function ] name () { list; }

      Dieses Konstrukt definiert eine bash-Funktion mit dem Namen name, ähnlich einem Unterprogramm. Die Anweisungen der Funktion werden durch { ..... } geklammert. Diese Liste wird immer dann ausgeführt, wenn die Funktion innerhalb der bash mit ihrem Namen name aufgerufen wird. Der exit-status der Funktion entspricht dem exit-status des letzten in der Funktion ausgeführten Kommandos. (Siehe den Abschnitt Funktionen)

  10. Kommentare

    Das Kommentarzeichen der bash ist # (Doppelkreuz). Alle Worte einer Zeile, die auf # folgen, werden durch die bash ignoriert. Ob Kommentare erlaubt sind oder nicht, entscheidet die bash-Option interactive_comments. In der default-Einstellung ist die Option auf on eingestellt.

  11. Quoting

    Quoting ist eine Methode, die besondere Bedeutung spezieller Zeichen und Worte in der shell zu deaktivieren. So kann zB. die besondere Bedeutung der metacharakter oder control operatoren unterbunden werden. Weiterhin ist es möglich, die Erkennung reservierte Worte oder die Expansion von Parametern zu verhindern. When the command history expansion facilities are being used, the history expansion character, usually !, must be quoted to prevent history expansion. Es gibt drei Arten des Quotings.

    1. escape character \ (backslash <AltGr>+ß)

      Ein nicht gequoteter backslash (\) ist der escape character. Der backslash hebt die Sonderbedeutung nur des folgenden Zeichens auf. Sollen mehrere Zeichen gequotet werden, so ist jedem dieser Zeichen ein backslash voranzustellen. Weiterhin können mit dem backslash auch nicht druckbare Zeichen erzeugt werden.
      Weitere backslash escape-sequenzen sind:

      \aalert (bell)
      \bbackspace
      \eescape character ESC 27
      \fform feed
      \nnew line
      \rcarriage return
      \thorizontal tab
      \vvertical tab
      \\backslash
      \'single quote
      \nnnZeichencode in oktaler Kodierung
      \xHHZeichencode in hexadezimaler Kodierung
      \cxcontrol-x character

      Eine besondere Bedeutung hat ein gequotetes <newline>, also die Zeichenkombination \<newline>, wobei der backslash nicht selbst gequotet sein darf. Diese escape-Sequenz bewirkt eine Fortsetzung der Eingabezeile auf der nächsten Terminalzeile. Der gequotete backslash wird dabei aus dem Datenstrom entfernt und ist effektiv nicht vorhanden. Damit kann die Eingabezeile auf mehrere Terminalzeilen ausgedehnt werden.

    2. single quotes ' (Ticks <Strg>+#)

      Alle Zeichen und Worte, die zwischen den single quotes ' eingeschlossen sind, verlieren ihre Sonderbedeutung, ausgenommen der single-quote selbst. In einem mit single-quotes gequoteten string darf selbst kein single-quote enthalten sein.

    3. double quotes " (Anführungszeichen <Schift>+2)

      Alle Zeichen und Worte, die zwischen den double quotes " eingeschlossen sind, verlieren ihre Sonderbedeutung, ausgenommen $,`, " und \. Die Zeichen $ und ` behalten ihre Bedeutung innerhalb der double quotes " bei. Der backslash wirkt mit seiner Sonderbedeutung nur noch, wenn er von einem der Zeichen $, `, ", \, or <newline> gefolgt wird. Innerhalb von double quotes müssen double quotes mit dem backslach gequotet werden. Die Parameter * und @ haben innerhalb der double quotes eine besondere Bedeutung. Die Ausdrücke der Form $'string' haben eine besondere Bedeutung.

  12. Parameter

    Parameter sind Konstrukte zum speichern von Werten. Parameter sind Variablen, die mit einem Namen referenziert werden. Der gespeicherte Wert kann eine Zahl, ein String auch mit Sonderzeichen, oder auch ein Nullstring sein. Der Parameter wird definiert, wenn ihm ein Wert zugeordnet wird. Diesen Parametern können auch verschiedene Attribute bei der Deklaration verliehen werden. Eine solche Variable wird durch folgende Anweisung angelegt:
    name=[value]
    Wenn kein Wert value angegeben wird, wird der Nullstring an die Variable übergeben. Alle Werte value werden vor der Zuweisung der Tilde-, Parameter-, Variablen-, Arithmetikexpansion, der Kommandosubstitution und dem Entquoten unterzogen.

    1. Positionsparameter

      Die Positionsparameter werden mit einer oder mehreren Ziffernstellen, beginnend mit 1, bezeichnet. Beim Start eines shell-Skripts werden automatisch von der shell erzeugt und erlauben den Zugriff auf die Argumente, die dem Script beim Aufruf übergeben wurden. Nachdem die bash die Expansionen durchgeführt hat, werden die Positionsparameter erzeugt und sind innerhalb des shell-Scriptes gültig. Der Positionsparameter $1 ernthält das erste übergebene Argument, $2 das zweite Argument usw. usf. Sollte die Bezeichnung des Positionsparameters mehrstellig sein, so ist sie in geschweifte Klammern zu setzen (brace-Expansion). Bei Aufruf einer shell-Funktion gelten innerhalb der shell-Funktion lokal eigene Positionsparameter, die die Argumente enthalten, die der shell-Funktion beim Aufruf mitgegeben wurden. Sie gelten nur innerhalb der Funktion.

    2. Spezialparameter

      Die shell stellt eine Reihe von Spezialparametern zur Verfügung. Diese Parameter können nur gelesen werden, eine Wertezuweisung ist nicht erlaubt.

      $*

      Expandiert die Positionsparameter $1...$9. $* enthält alle Positionsparameter separiert durch das erste Zeichen aus der Variable IFS. Wenn die Expansion innerhalb von double quotes erfolgt, dann ist das Ergebnis ein Wort, das alle Argumente, separiert durch das Trennzeichen, enthält. Ist IFS nicht gesetzt, wird das Leerzeichen als Separator verwendet. Ist IFS mit einem Nullstring belegt, so werden die Positionsparameter ohne Trennzeichen gelistet.

      $@

      Expandiert die Positionsparameter $1...$9. Wenn die Expansion innerhalb von double quotes erfolgt, dann ist das Ergebnis eine Liste von Worten der Form "$1" "$2",... Wenn keine Argumente übergeben wurden, so werden $@ und "$@" zu einem Nullstring expandiert.

      $#Expandiert die Anzahl der Positionsparameter dezimal.
      $?exit-status, Rückgabewert der letzten synchron ausgeführten Pipeline.
      $-Expandiert die beim shellstart gesetzten Optionen.
      $$Expandiert die Prozessnummer des gerade laufenden shell-Prozesses. Innerhalb einer Subshell wird ebenfalls die Prozessnummer der Muttershell und nicht der Subshell ausgegeben.
      $!Expandiert die Prozessnummer des zuletzt asynchron ausgeführten Hintergrundprozesses.
      $0

      Expandiert den Namen der Shell oder des Shellscriptes. Sie ist bereits bei der Initialisierung der Shell gesetzt. Wenn die Shell in ein Shellscript included wurde, dann enthält $0 den Namen des Shellscriptes. If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the file name used to invoke bash, as given by argument zero.

      $_ At shell startup, set to the absolute file name of the shell or shell script being executed as passed in the argument list. Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full file name of each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked.
  13. Shell Variablen

    Die folgenden Variablen sind innerhalb der shell gesetzt:
    BASHEnthält den vollen Pfad und Dateinamen der laufenden shell
    BASH_VERSINFO Enthält die Versionsinformationen der laufenden bash. Dabei handelt es sich um ein nur-lesbares Array mit folgendem Inhalt
    BASH_VERSINFO[0]Release-Nummer
    BASH_VERSINFO[1]Versionsnummer
    BASH_VERSINFO[2]Patch-Level
    BASH_VERSINFO[3]Build-Version
    BASH_VERSINFO[4]Releasestatus
    BASH_VERSINFO[5]MACHTYPE.
    BASH_VERSIONEnthält einen Versionsstring der laufenden bash
    COMP_CWORD An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Pro­ grammable Completion below).
    COMP_LINE The current command line. This variable is avail­ able only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below).
    COMP_POINT The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the cur­ rent command, the value of this variable is equal to ${#COMP_LINE}. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Pro­ grammable Completion below).
    COMP_WORDS An array variable (see Arrays below) consisting of the individual words in the current command line. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion below).
    DIRSTACK

    Array, um auf den Directory-Stack zuzugreifen. Dieser wird mit den Kommandos pushd, popd und dirs verwaltet.

    EUID

    Enthält die effective User-ID. Diese wird z.B. während der Ausführung von Programmen mit gesetztem SUID-Bit angepasst. Diese Variable kann nur gelesen werden.

    FUNCNAME

    Enthält den Namen der momentan ausgeführten Shell-Funktion. Diese Variable existiert nur, wenn die Shell eine Funktion ausführt. Zuweisungen an diese Variable haben keinen Effekt und werden mit dem exit-Status 1 (falsch) quittiert.

    GROUPS

    Array mit einer Liste aller Gruppen-IDs des aktuellen Benutzers. Zuweisungen an diese Variable haben keinen Effekt und werden mit dem exit-Status 1 (falsch) quittiert.

    HISTCMD The history number, or index in the history list, of the current command. If HISTCMD is unset, it loses its special properties, even if it is subse­ quently reset.
    HOSTNAME Wird automatisch auf den Namen des Rechners gesetzt.
    HOSTTYPE Automatically set to a string that uniquely describes the type of machine on which bash is exe­ cuting. The default is system-dependent.
    LINENO

    Enthält immer die aktuelle Zeilennummer im Shellscript. Wird die Variable in einem Shellscript aufgerufen, so entspricht ihr Wert den bis zum Aufruf innerhalb des Scriptes ausgeführten einfachen Kommandos. Außerhalb von Shellscripten ist die Variable nicht sinnvoll belegt. Wird sie mit unset gelöscht, so wird sie innerhalb der Shell nicht wieder automatisch gesetzt.

    MACHTYPE

    Automatisch generierter String, der die CPU-Architektur beschreibt, auf der das System läft.

    OLDPWD Das vorher durch cd aufgerufene Arbeitsverzeichnis.
    OPTARG

    Argument der zuletzt von getopts ausgewerteten Option

    OPTIND

    Enthät die Indexnummer der zuletzt von getopts ausgewerteten Option

    OSTYPE

    Wird automatisch mit dem Namen des Betriebssystems gesetzt. Der Angabe ist sehr unzuverlässig und es sollte eher uname benutzt werden

    PIPESTATUS

    Enthält ein Array mit dem exit-Code der zuletzt im Vordergrund ausgeführten Kommandosequenz. Wenn es sich dabei um eine Pipe gehandelt hat, so sind die exit-Codes aller Kommandos innerhalb der Pipe in diesem Array abgelegt.

    PPID

    Enthält die Prozessnummer des Elternprozesses, der die shell gestartet hat.

    PWD

    Das aktuelle Arbeitsverzeichnis, das durch cd gesetzt wurde.

    RANDOM

    Enthält bei jedem Lesezugriff eine neue ganzzahlige Zufallszahl aus dem Bereich 0 .... 32767

    REPLY

    Hier legt das built-in Kommando read die gelesene Eingabezeile ab, wenn kein Parameter übergeben wurde. In select-Menüs enthält REPLY die ausgewählte Nummer.

    SECONDS

    Enthält die seit dem Start der shell vergangene Zeit in Sekunden. Für jede gestartete Subshell startet diese Variable ebenfalls mit Null. Wird SECONDS ein Wert zugewiesen, so erhöht sih dieser jede Sekunde weitergezählt.

    If SECONDS is unset, it loses its special properties, even if it is subsequently reset.
    SHELLOPTS

    Enthält eine durch Doppelpunkte separierte Liste aller aktiven shell-Optionen.

    SHLVL

    Wird immer um Eins erhöht, wenn eine weitere Instance der Bash (Subshell) gestartet wird.

    UID Enthält die User-ID des Benutzers, der die laufende shell gestartet hat.

    Die folgenden Variablen werden von der bash genutzt. In einigen Fällen sind diese Variablen auf Defaultwerte gesetzt. Diese sind dann entsprechend mit angegeben.

    BASH_ENV

    Diese Variable wird durch die bash gelesen, wenn ein shell-Script ausgeführt wird. Sie enthält den Namen einer Initialisierungsdatei, die beim Start einer neuen Subshell anstatt .bashrc ausgeführt wird. Es wird vor der Ausführung eine Parameterexpansion, Komandosubstitution und eine Arithmetikexpansion durchgeführt. Das File wird nicht in PATH gesucht.

    CDPATH

    Enthält den Suchpfad für das cd-Kommando. Es handelt sich um eine durch Doppelpunkte getrennte Liste von Verzeichnisnamen.(z.B. ".:~:/usr")

    COLUMNS

    Enthält die Breite des Editorfensters, das für den Kommandozeileneditor und die Menüs zur Verfügung steht. Der Standardwert ist 80. Bei Empfang der Signals SIGWINCH wird diese Variable automatisch gesetzt.

    COMPREPLY

    An array variable from which bash reads the possi­ ble completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion below).

    FCEDIT

    Pfad zum Builtin-Editor für das fc-Kommando

    FIGNORE

    Enthält eine durch Doppelpunkte getrennte Liste der Suffixe von Dateinamen, die beim Autovervollständigen (TAB) ignoriert werden sollen. (z.B. ".o:.bak:~")

    GLOBIGNORE

    Enthält eine durch Kommata getrennte Liste von Mustern, die Namen definiert, welche bei der Dateinamen-Expansion durch * ? [] nicht automatisch expandiert werden sollen.

    HISTCONTROL If set to a value of ignorespace, lines which begin with a space character are not entered on the his­ tory list. If set to a value of ignoredups, lines matching the last history line are not entered. A value of ignoreboth combines the two options. If unset, or if set to any other value than those above, all lines read by the parser are saved on the history list, subject to the value of HISTIG­ NORE. This variable's function is superseded by HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL.
    HISTFILE

    Pfadname zur History-Befehlsdatei. Der Standardwert ist $HOME/.bash_history. Wenn die Variable nicht gesetzt ist, wird keine Befehlshistory geführt.

    HISTFILESIZE

    Gibt die Maximalanzahl der in der Historydatei vorgehaltenen Befehle an. Der Defaultwert ist 500.

    HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempt­ ing a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE.
    HISTSIZE

    Gibt die Anzahl der in der Historydatei vorgehaltenen Befehle an.

    HOME

    Heimatverzeichnis der Users. Es ist der Standardwert für cd und der Wert der für die Tildeexpansion.

    HOSTFILE Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.
    IFS

    Der IFS (Internal Field Separator) wird nach der Expansion für das Wordsplitting durch das read-Komando benutzt. Dieser enthält die Trennzeichen, mit denen die einzelnen Worte der Eingabezeile voneinander getrennt werden. Der Defaultwert dieser Variable ist "<space><tab><newline>".

    IGNOREEOF Controls the action of an interactive shell on receipt of an EOF character as the sole input. If set, the value is the number of consecutive EOF characters which must be typed as the first charac­ ters on an input line before bash exits. If the variable exists but does not have a numeric value, or has no value, the default value is 10. If it does not exist, EOF signifies the end of input to the shell.
    INPUTRC The filename for the readline startup file, over­ riding the default of ~/.inputrc (see READLINE below).
    LANG Used to determine the locale category for any cate­ gory not specifically selected with a variable starting with LC_.
    LC_ALL This variable overrides the value of LANG and any other LC_ variable specifying a locale category.
    LC_COLLATE This variable determines the collation order used when sorting the results of pathname expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within pathname expansion and pattern matching.
    LC_CTYPE This variable determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern matching.
    LC_MESSAGES This variable determines the locale used to trans­ late double-quoted strings preceded by a $.
    LC_NUMERIC This variable determines the locale category used for number formatting.
    LINES Used by the select builtin command to determine the column length for printing selection lists. Auto­ matically set upon receipt of a SIGWINCH.
    MAIL If this parameter is set to a file name and the MAILPATH variable is not set, bash informs the user of the arrival of mail in the specified file.
    MAILCHECK Specifies how often (in seconds) bash checks for mail. The default is 60 seconds. When it is time to check for mail, the shell does so before dis­ playing the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.
    MAILPATH A colon-separated list of file names to be checked for mail. The message to be printed when mail arrives in a particular file may be specified by separating the file name from the message with a `?'. When used in the text of the message, $_ expands to the name of the current mailfile. Exam­ ple: MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"' Bash supplies a default value for this variable, but the location of the user mail files that it uses is system dependent (e.g., /var/mail/$USER).
    OPTERR If set to the value 1, bash displays error messages generated by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTERR is initialized to 1 each time the shell is invoked or a shell script is executed.
    PATH

    Enthält den Suchpfad für Kommandos. Es handelt sich dabei um eine durch Doppelpunkte getrennte Liste von Verzeichnissen in denen nach einem Kommando gesucht wird, das ohne Pfadangabe aufgerufen wird. Standardwert ist PATH=:/bin:/usr/bin

    POSIXLY_CORRECT If this variable is in the environment when bash starts, the shell enters posix mode before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, bash enables posix mode, as if the command set -o posix had been executed.
    PROMPT_COMMAND If set, the value is executed as a command prior to issuing each primary prompt.
    PS1

    Enthält den Primärprompt. Er ist der Prompt zur Befehlseingabe. Innerhalb des Strings sind in der bash bestimmte Sonderzeichen erlaubt, die eine besondere Bedeutung besitzen. Der Backslash leitet dabei eine Escapesequenz ein. Folgende Sonderzeichen werden expandiert:

    ZeichenBedeutung
    \tDie aktuelle Uhrzeit im Format "HH:MM:SS"
    \dDas aktuelle Tagesdatum im Format "Wochentag Monat Tag"
    \nZeilenvorschub
    \sDer Name der Shell
    \wDas aktuelle Arbeitsverzeichnis. Befindet man sich im Homeverzeichnis, so wird eine Tilde angezeigt
    \uDer Benutzername
    \hDer Rechnername
    \!Laufende Kommandonummer
    \nnnoctale Notation eines ASCII-Zeichens
    \\Backslash

    Der Defaultwert ist "\s-\v\$ ".

    PS2

    Enthält den Sekundärprompt. Er wird für mehrzeilige Befehle verwendet. Der Defaultwert ist >.

    PS3

    Enthält den Promptstring für Menüs (mit select). Defaultwert ist #.

    PS4

    Enthält den Debugging-Promptstring für die Option -x. Der Defaultwert ist +.

    TIMEFORMAT

    Ausgabeformat des time-Kommandos.
    Das %-Zeichen leitet eine Escapesequenz ein, in der die verschiedenen Zeitwerte expandiert werden. Diese Escapesequenzen haben die folgenden Bedeutungen.

    %%Erzeugt das Zeichen %
    %[p][l]RInsgesamt verbrauchte Zeit in Sekunden
    %[p][l]UAnzahl der Sekunden verbrauchter Benutzerzeit
    %[p][l]SAnzahl der Sekunden verbrauchter CPU-Zeit
    %Pprozentuale Angabe der verbrauchten CPU-Zeit, entspricht (%U + %S)/ %R

    Der optionale Parameter p gibt die Anzahl der Stellen nach dem Komma, mit denen der Wert angezeigt werden soll. Der Wert 0 (Null) bedeutet, das keine Stellen nach dem Komma angezeigt werden sollen. Der größte Wert für p ist 3, wird ein größerer Wert angegeben, so wird p auf 3 gesetzt. Wird kein Wert für p angegeben, so ist der default-Wert 3.
    Der optionale Parameter l legt das long-Format fest. Es enthält die Angabe der Minuten und Stunden in der Form MMmSS.FFs. Der Parameter p gibt dann The value of p determines whether or not the fraction is included.
    Wenn die Variable nicht gesetzt ist, benutzt die bash den Wert $'\nreal\t%3lR\nuser\t%3lU\nsys%3lS'. Wenn der Wert der Variable ein Nullstring ist, wird keinerlei Zeitinformation durch time ausgegeben. Ansonsten wird eine abschließende Zeilenschaltung ausgegeben.

    TMOUT

    TIMEOUT-Wert. Wenn TMOUT Sekunden lang kein Kommando mehr eingegeben wurde, so beendet sich die bash. Der Wert 0 (Null) steht für unendlich.

    auto_resume This variable controls how the shell interacts with the user and job control. If this variable is set, single word simple commands without redirections are treated as candidates for resumption of an existing stopped job. There is no ambiguity allowed; if there is more than one job beginning with the string typed, the job most recently accessed is selected. The name of a stopped job, in this context, is the command line used to start it. If set to the value exact, the string supplied must match the name of a stopped job exactly; if set to substring, the string supplied needs to match a substring of the name of a stopped job. The substring value provides functionality analo­ gous to the %? job identifier (see JOB CONTROL below). If set to any other value, the supplied string must be a prefix of a stopped job's name; this provides functionality analogous to the % job identifier.
    histchars

    Enthält zwei Zeichen zur Kontrolle der Wiederholung von Kommandos aus dem Kommandozeilenspeicher. Das erste Zeichen leitet eine Kommandozeilenerweiterung aus dem History-Puffer ein. Die Voreinstellung ist das !-Zeichen. Das zweite Zeichen kennzeichnet einen Kommentar, wenn es das erste Zeichen eines Wortes ist. Ein solcher Kommentar wird bei der Ausführung eines Kommandos ignoriert.

  14. Arrays

    Die bash unterstützt eindimensionale Arrays. Jede Variable kann als Array angesprochen werden. Es ist nicht notwendig, ein Array vor der Benutzung zu definieren, man kann dies jedoch mit declare und typeset tun. Mit
    declare -a name
    wird die Variable name explizit als Array deklariert. Eine Zuweisung von Attributen ist ebenfalls möglich. Mit
    typeset -i name
    z.B. wird festgelegt, dass die Elemente des Arrays name nur aus Integerzahlen bestehen. Dabei wird keine Obergrenze für den Index angegeben und es ist auch nicht notwendig, die Arrayelemente fortlaufend zu indizieren. Der Index ist eine nicht negative Integerzahl, die Indizierung beginnt mit Null. Ein Array wird bei der ersten Wertezuweisung automatisch durch die bash erzeugt. Grundsätzlich gibt es zwei Möglichkeiten der Wertezuweisung.

    1. Einzelwertzuweisung
      Durch die Syntax:
      name[subscript]=value
      wird einem einzelnen Arrayelement im Array name ein Wert zugewiesen, wobei subscript selbst ein arithmetischer Ausdruck ist, der einen Integerwert>=0 liefert.
    2. Listenzuweisung
      Durch die Syntax:
      name=(wert1 wert2 wert3 ... )
      wird das Array name neu mit Werten initialisiert. Die vorher im Array gespeicherten Werte gehen verloren. Die einzelnen Werte haben die Form [substring]=string , wobei string erforderlich ist. Wenn [substring]= mit angegeben wird, dann wird der string in das entsprechende Arrayelement gespeichert. substring wird als Index für das Arrayelement verwendet. Fehlt die Angabe [substring]=, so wird der Index fortlaufend um eins erhöht und die strings in aufeinanderfolgenden Arrayelementen gespeichert. Wird in der ganzen Liste überhaupt kein substring angegeben, so startet der Index bei Null.

    Auf die einzelnen Elemente eines Arrays name kann man mit ${name[subscript]} zugreifen. Die geschweiften Klammern sind erforderlich, um Konflikte mit der Pathname-Expansion zu vermeiden. Wenn subscript mit @ oder * angegeben wird, so werden alle Elemente des Arrays expandiert. Die subscripts @ und * unterscheiden sich, wenn die Worte in Anführungszeichen gesetzt werden.
    "${name[@]}" expandiert die Elemente des Arrays name in eine Liste von Einzelworten, die durch Trennzeichen (im allgemeinen das erste Zeichen der shell-Variable IFS, also das Leerzeichen) voneinander separiert sind.
    "${name[*]}" expandiert die Elemente des Arrays name als ein Wort, das den Inhalt der Elemente durch Trennzeichen (im allgemeinen das erste Zeichen der shell-Variable IFS, also das Leerzeichen) separiert, enthält. Wenn das Array name keine Elemente enthält, werden beide Formen zu Nullstrings expandiert. ${#name[subscript]} gibt an, wie lang der in ${name[subscript]} abgelegte Wert ist.
    ${#name[*]} und ${#name[@]} gibt die Anzahl der Elemente des Arrays name zurück.
    Wenn kein subscript angegeben wird, so erfolgt der Zugriff auf das Element mit der Indexnummer Null. Mit dem unset-Kommando können einzelne Arrayelemente oder ganze Arrays gelöscht werden.
    unset name[subscript] löscht das indizierte Arrayelement des Arrays name.
    unset name löscht das komplette Array name.
    unset name[*] oder unset name[@] löscht alle Elemente des Arrays name.
    Die shell-Befehle declare, local und readonly können mit der Option -a auf Arrays angewendet werden. Der shell-Befehl read akzeptiert ebenfalls die Option -a und legt dann die an STDIN gelesenen Daten in einem Array ab.

  15. Expansion

    Die Expansion der Kommandozeile wird durch die bash durchgeführt, bevor das eigentliche Kommando aufgerufen wird. Die Expansion wird gestartet, nachdem der Inhalt der Kommandozeile anhand der Trennzeichen separiert wurde. Die Expansion wird in mehreren Schritten in folgender Reihenfolge durchgeführt:
    1. Brace Expansion
    2. Tilde Expansion
    3. Parameter Expansion
    4. Arithmetic Expansion
    5. Kommandosubstitution (done in a left-to-right fashion)
    6. Wordsplitting
    7. Pathname Expansion
    8. Prozesssubstitution
    Nur Brace Expansion, Wordsplitting und Pathname Expansion können die Anzahl der Worte im expandierten String verändern. Alle anderen Expansionen expandieren ein Wort in ein anderes Wort. Die einzigen Ausnahmen sind die Expansionen von "$@$" und "${name[@]}". Siehe in den Abschnitten Parameter und Arrays.
    1. Brace Expansion

      Die Brace-Expansion ist eine Möglichkeit der bash, verschiedene Stringmuster zu erzeugen. Eine gültige Brace Expansion bestehen aus einem optionalen Präfix, gefolgt von in ungequoteten geschweiften Klammern, durch ungequotete Kommata separierten Alternativ-Ausdrücken, denen ein optionaler Suffix folgt. Die Syntax lautet allgemein:
      präfix{ muster1, muster2, ... }suffix
      Dieses Muster wird durch die bash in eine Reihe von Strings expandiert, dazu wird vor jedes Muster muster1, muster2,... der Präfix gesetzt und der Suffix angehängt. Das Ergebnis der Expansion ist nicht sortiert, sondern die Expansion wird von links nach rechts abgearbeitet.
      Ein Beispiel:
      Das Muster a{d,c,b}e wird durch die bash in "ade ace abe" expandiert.
      Die Brace-Expansion wird als erste, vor allen anderen Expansionen durchgeführt. Die Brace-Expansion läuft zeichenorientiert ab. Es findet keinerlei syntaktische Interpretation der geklammerten Alternativ-Ausdrücke statt, deshalb bleiben auch Spezialzeichen anderer Expansionsarten erhalten und können in der Brace-Expansion verwendet werden um nachfolgend expandiert zu werden. Sollten die Alternativ-Ausdrücke die Zeichen {} oder , enthalten, so sind sie mit dem backslash zu quoten. Eine unkorrekte Brace-Expansion wird nicht ausgeführt. Die bash gibt eine Fehlermeldung auf STANDARDERR aus. Um Konflikte mit der nachfolgenden Parameterexpansion zu vermeiden, sollte man den String ${ wohlüberlegt einsetzten. Die Brace-Expansion ist ein sehr vorteilhaftes Werkzeug, wenn viele Ausdrücke erzeugt werden sollen, die sich nur gering unterscheiden und der Präfix recht lang ist.
      Beispiele:
      Das Kommando
      mkdir /usr/local/src/bash/{old,new,dist,bugs}
      legt nacheinander die Verzeichnisse /usr/local/src/bash/old, /usr/local/src/bash/new, /usr/local/src/bash/dist und /usr/local/src/bash/bugs an. Das Kommando
      chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
      führt nacheinander ein chown für die Dateien /usr/ucb/ex, /usr/ucb/edit, /usr/lib/ex?.?* und /usr/lib/how_ex aus. Die Brace-Expansion der bash wird in der shell (/bin/sh) nicht unterstützt. Mit der Startoption -B kann die Brace-Expansion der bash abgeschaltet werden.

    2. Tilde Expansion

      Wenn ein Wort mit einer ungequoteten Tilde ~ beginnt, werden alle Zeichen bis zum ersten ungequoteten slash in die Tildeexpansion eingeschlossen und als Tildepräfix behandelt. Die Tildeexpansion wird unter folgenden Bedingungen durchgeführt:
      TildepräfixBedeutung
      ~

      Der Tildepräfix ist ein Nullstring. Die Tilde wird mit dem Inhalt der shell-Variable HOME expandiert. Wenn HOME nicht gesetzt ist, wird die Tilde durch den Pfad des Homeverzeichnises des Benutzers ersetzt, der die shell ausführt.

      ~BENUTZERNAME

      Wenn der Tildepräfix aus ungequoteten Zeichen besteht und einem Benutzernamen des Systems entspricht, wird mit dem Homeverzeichnis dieses Users expandiert. Ist der Benutzername unbekannt, so wird keine Tildeexpansion durchgeführt und der String bleibt unverändert.

      ~-

      Wenn der Tildepräfix nur aus dem Zeichen - besteht, so wird bei der Tildeexpansion das zuvor besuchte Verzeichnis (OLDPWD) eingesetzt.

      ~+

      Wenn der Tildepräfix nur aus dem Zeichen + besteht, so wird bei der Tildeexpansion der Name des aktuellen Arbeitsverzeichnises (pwd) eingesetzt.

      In jeder Variablenzuweisung wird auf einen ungequoteten Tildepräfix getestet, der einem = oder : folgt. In diesem Fall wird ebenfalls eine Tildeexpansion durchgeführt. Dadurch können Tildeexpansionen auch in der Zuweisung der Variablen PATH, MAILPATH und CDPATH verwendet werden.

    3. Parameter Expansion

      Das Zeichen $ leitet eine Parameterexpansion, Kommandosubstitution oder Arithmetikexpansion ein. Die Verwendung der geschweiften Klammer (brace) stellt dabei sicher, dass der zu expandierende Parametername eindeutig zu identifizieren ist wenn ihm unmittelbar weitere Zeichen folgen. Wenn die geschweifte Klammerung benutzt wird, so wird das Ende des Parameters durch das erste nicht gequotete oder in Kommandosubstitutionen oder Arithmetikexpansionen eingebettete Auftreten der geschlossenen geschweiften Klamer } festgelegt.
      Expansionen:

      ${parameter}

      Der Parameter parameter wird durch seinen Wert ersetzt. Die Klammern sind notwendig, wenn es sich um einen Positionsparameter mit mehr als einer Stelle handelt, oder dem Parameternamen unmittelbar weitere Zeichen folgen und fälschlicherweise als Teil des Parameternamens interpretiert werden könnten.

      ${parameter:-word}

      Defaultwert-Definition.
      Wenn der Parameter parameter nicht definiert ist oder einen NULL-String enthält, wird er mit word expandiert, ansonsten durch den Wert, den der Parameter enthält.

      ${parameter:=word}

      Defaultwert-Zuweisung.
      Wenn der Parameter parameter nicht definiert ist oder einen NULL-String enthält, wird ihm der Defaultwert word zugewiesen. Danach wird der Parameter durch seinen Wert expandiert.
      Positionsparameter und Spezialparameter kö,nnen nicht auf diese Weise expandiert werden.

      ${parameter:?word}

      Wenn der Parameter parameter nicht existiert oder einen Nullstring enthält, wird eine durch die shell die Fehlermeldung word auf STANDARDERR ausgegeben und wenn die shell nicht interaktiv ist, die shell durch ein exit verlassen. Ansonsten wird der Parameter durch seinen Wert substituiert.

      ${parameter:+word}

      Wenn der Parameter parameter nicht existiert oder einen Nullstring enthält, wird er mit einem Nullstring expandiert. Ansonsten wird der Parameter durch word substituiert.

      ${parameter:offset}
      ${parameter:offset:length}

      Substring Expansion
      Expandiert einen Teilstring des Parameters parameter ab der Zeichenposition offset mit der Länge length. Wenn keine Länge angegeben wird, dann wird der gesamte Teilstring ab offset bis zum Ende des Parameterinhaltes zurückgeliefert. offset und lengt können selbst wieder arithmentische Ausdrücke sein. length muss ein ganzzahliger Integerwert>=0 sein. Ist offset ein negativer Integerwert, so wird er als Offsetwert vom Ende des Parameterinhaltes an gezählt.

      ${!prefix*}

      Expandiert die Namen aller Variablen die mit dem Prefix prefix beginnen. Die Liste wird mit dem ersten Zeichen aus IFS als Trennzeichen (im Normalfall das Leerzeichen) erstellt.

      ${#parameter}

      Es wird die Anzahl der Zeichen im Inhalt des Parameters zurückgeliefert. Ist der Parameter @ oder *, so wird die Anzahl der verfügbaren Positionsparameter expandiert. Ist der Parameter ein Array, so ist es die Anzahl der Elemente im Array parameter.

      ${parameter#word}
      ${parameter##word}

      Es wird mit dem Inhalt des Parameters parameter substituiert, wobei dieser zuvor nach dem Suchmuster word durchsucht wird.
      In der Form ${parameter#word} wird der kleinstmögliche, durch das Suchmuster abgedeckte, linke Teilstring aus dem Ergebnis entfernt.
      In der Form ${parameter##word} wird der größtmögliche, durch das Suchmuster abgedeckte, linke Teilstring aus dem Ergebnis entfernt.
      Wenn der Parameter @ oder * ist, so wird die Operation auf alle verfügbaren Positionsparameter angewendet und dann die Ergebnisliste erzeugt. Ist der Parameter ein Array mit dem subscript @ oder *, so wird die Operation auf alle Elemente des Arrays angewendet und dann die Ergebnisliste erzeugt. Bei allen Operationen bleibt der ursprüngliche Inhalt des Parameters parameter unverändert. Die Operation wird nur innerhalb der Expansion ausgeführt.

      ${parameter%word}
      ${parameter%%word}

      Es wird mit dem Inhalt des Parameters parameter substituiert, wobei dieser zuvor nach dem Suchmuster word durchsucht wird.
      In der Form ${parameter%word} wird der kleinstmögliche, durch das Suchmuster abgedeckte, rechte Teilstring aus dem Ergebnis entfernt.
      In der Form ${parameter%%word} wird der größtmögliche, durch das Suchmuster abgedeckte, rechte Teilstring aus dem Ergebnis entfernt.
      Wenn der Parameter @ oder * ist, so wird die Operation auf alle verfügbaren Positionsparameter angewendet und dann die Ergebnisliste erzeugt. Ist der Parameter ein Array mit dem subscript @ oder *, so wird die Operation auf alle Elemente des Arrays angewendet und dann die Ergebnisliste erzeugt. Bei allen Operationen bleibt der ursprüngliche Inhalt des Parameters parameter unverändert. Die Operation wird nur innerhalb der Expansion ausgeführt.

      ${parameter/word/string}
      ${parameter//word/string}

      Es wird mit dem Inhalt des Parameters parameter substituiert, wobei dieser zuvor nach dem Suchmuster word durchsucht wird.
      In der Form ${parameter/word/string} wird der Inhalt des Parameters vom Beginn an nach dem größtmöglichen, durch das Suchmuster abgedeckten Teilstring durchsucht und dieser durch das Wort string einmalig ersetzt.
      In der Form ${parameter//word/string} wird der größtmögliche, durch das Suchmuster abgedeckte Teilstring, bei jedem Auftreten durch das Wort string ersetzt.
      Wenn der Suchstring word mit # beginnt, so wird das Suchmuster nur am Anfang des Inhaltes des Parameters parameter getestet.
      Wenn der Suchstring word mit % beginnt, so wird das Suchmuster nur am Ende des Inhaltes des Parameters parameter getestet.
      string kann auch ein Nullstring sein, wodurch die entsprechenden Zeichen nicht erzetzt, sondern gelöscht werden. Wenn der Parameter @ oder * ist, so wird die Operation auf alle verfügbaren Positionsparameter angewendet und dann die Ergebnisliste erzeugt. Ist der Parameter ein Array mit dem subscript @ oder *, so wird die Operation auf alle Elemente des Arrays angewendet und dann die Ergebnisliste erzeugt. Bei allen Operationen bleibt der ursprüngliche Inhalt des Parameters parameter unverändert. Die Operation wird nur innerhalb der Expansion ausgeführt.

    4. Arithmetic Expansion

      Die Arithmetic-Expansion erlaubt die Berechnung arithmetischer Ausdrücke und die Expansion durch das Ergebnis.
      Das Format einer Arithmetic-Expansion ist:
      $((expression))
      The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. Die einzelnen Teile des arithmetischen Ausdrucks expression durchlaufen vorher die Parameterexpansion, die Stringexpansion, Kommandosubstitution und das Entquoten. Die Berechnung erfolgt nach den im Abschnitt "Arithmetische Berechnungen" beschriebenen Regeln. Sollte der arithmetische Ausdruck fehlerhaft sein, so erzeugt die bash eine Fehlermeldung auf STANDARDERR und führt keine Expansion aus.

    5. Kommandosubstitution

      Die Kommandosubstitution erlaubt es, den Kommandoaufruf durch die Ausgabe des Kommandos zu ersetzen (substituieren). Die Syntax erlaubt zwei unterschiedliche Formen:
      $(command)
      oder
      `command`
      Die bash wird dann das Kommando command ausführen und den Kommandoaufruf durch die Ausgabe auf STANDARDOUT substituieren. Aus dem Ausgabedatenstrom werden, bis auf ein abschließendes <newline>-Zeichen, alle anderen durch ein Trennzeichen (im allgemeinen das Leerzeichen) ersetzt. Die Kommandosubstitution $(cat file) kann durch das schnellere Äquivalent $(< file) ersetzt werden.

    6. Word Splitting

      Die Shell durchsucht die Ergebnisse der Parameterexpansion, Kommandosubstitution und Arithmeticexpansion, die nicht durch " (double-quotes, doppelte Anführungszeichen) gequotet wurden mit dem wordsplitting. Die Shell behandelt jedes Zeichen von IFS als Trennzeichen, und teilt das Ergebnis der Expansionen in Worte auf. Wenn IFS nicht gesetzt ist, oder dessen Wert genau der Standardwert <space><tab><newline> ist, dann dient jede Folge der Zeichen <space><tab><newline> zur Abgrenzung der Worte. Wenn IFS einen anderen Wert als den Standardwert besitzt, dann werden <space><tab> als Trennzeichen für Anfang und Ende eines Wortes ignoriert und nur das IFS-Zeichen wird als Trennzeichen interpretiert. Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs. Explizite Null-Argumente ( "" oder'') werden beibehalten. Ungequotete implizite Null-Argumente, die sich aus der Expansion von Parametern ergeben und die keine Werte enthalten, werden entfernt. Wenn ein in doppelten Anführungszeichen gequoteter Parameter ohne Wert expandiert wird, so ist das Ergebnis ein Null-Argument und wird beibehalten. Wenn keine Expansion stattfindet, dann wird auch kein wordsplitting durchgeführt.

    7. Pathname Expansion

      After word splitting, unless the -f option has been set, bash scans each word for the characters *, ?, and [. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of file names matching the pattern. If no matching file names are found, and the shell option nullglob is disabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the shell option nocaseglob is enabled, the match is performed without regard to the case of alpha­ betic characters. When a pattern is used for pathname expansion, the character ``.'' at the start of a name or immediately following a slash must be matched explicitly, unless the shell option dotglob is set. When matching a pathname, the slash character must always be matched explicitly. In other cases, the ``.'' character is not treated specially. See the description of shopt below under SHELL BUILTIN COMMANDS for a description of the nocaseglob, nullglob, and dotglob shell options. The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. The file names ``.'' and ``..'' are always ignored, even when GLOBIGNORE is set. However, setting GLOBIGNORE has the effect of enabling the dotglob shell option, so all other file names beginning with a ``.'' will match. To get the old behavior of ignoring file names beginning with a ``.'', make ``.*'' one of the pat­ terns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset.
    8. Process Substitution

      Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files. It takes the form of <(list) or >(list). The pro­ cess list is run with its input or output connected to a FIFO or some file in /dev/fd. The name of this file is passed as an argument to the current command as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. If the <(list) form is used, the file passed as an argument should be read to obtain the output of list. When available, process substitution is performed simulta­ neously with parameter and variable expansion, command substitution, and arithmetic expansion.
  16. Pattern Matching

    In den Suchmustern (Pattern) kann jedes Zeichen, das keines der unten beschriebenen Spezial-Pattern ist, verwendet werden, um nach dem Zeichen selbst zu suchen. Das NUL-Zeichen darf in Mustern nicht enthalten sein. Die Spezial-Pattern müssen gequotet werden, wenn sie ihre Sonderbedeutung verlieren sollen und als Zeichen zu betrachten sind. Die Spezial-pattern haben die folgende Bedeutung:
    *schließt jedes Zeichen ein, auch den Nullstring.
    ?schließt ein einzelnes beliebiges Zeichen ein.
    [...] Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; any character that sorts between those two characters, inclusive, using the current locale's collating sequence and character set, is matched. If the first character following the [ is a ! or a ^ then any character not enclosed is matched. The sorting order of characters in range expressions is determined by the current locale and the value of the LC_COLLATE shell variable, if set. A - may be matched by including it as the first or last character in the set. A ] may be matched by including it as the first character in the set. Within [ and ], character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX.2 stan­ dard: alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit A character class matches any character belonging to that class. The word character class matches letters, digits, and the character _. Within [ and ], an equivalence class can be speci­ fied using the syntax [=c=], which matches all characters with the same collation weight (as defined by the current locale) as the character c. Within [ and ], the syntax [.symbol.] matches the collating symbol symbol.
    If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Com­ posite patterns may be formed using one or more of the following sub-patterns:
    ?(pattern-list) Matches zero or one occurrence of the given patterns
    *(pattern-list) Matches zero or more occurrences of the given patterns
    +(pattern-list) Matches one or more occurrences of the given patterns
    @(pattern-list) Matches exactly one of the given patterns
    !(pattern-list) Matches anything except one of the given patterns
  17. Quote Removal

    After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the above expansions are removed.
  18. Umleitung von Datenströmen

    Die Fähigkeit, Datenströme umzuleiten, ist eine sehr leistungsfähige und bedeutsame Eigenschaft der Linux-shell. Im Noramllfall geht man von drei Datenströmen aus, die auch Kanäle genannt werden. In der shell gibt es drei solcher Kanäle:

    Der Standardinput hat also keine Verbindug zum Terminalbildschirm. Das die eingegebenen Zeichen trotzdem sofort auf dem Bildschirm erscheinen ist keine Eigenschaft der shell, sondern des Terminals selbst (stty -echo). Erst mit der Enter-Taste wird das Terminal die Eingabezeile an den Standardinput der shell senden. Wenn jedoch Einzelzeichen gelesen werden sollen, so ist das Terminal entsprechend zu programmieren (siehe stty).
    Bevor die shell ein Kommando ausführt, interpretiert sie die Eingabezeile und scannt sie auf entsprechende Zeichen zur Umleitung der Datenkanäle von links nach rechts. Das eventuell notwendige Öffnen und Schliessen von Dateien zur Umleitung wird noch vor der Ausführung des Kommandos durch die shell vorgenomen. Die Umleitung von Datenströmen wird durch eine spezielle Notation mit den Operatoren <, >, & sowie der entsprechenden Kanalnummer vorgenommen. Die Notation zur Umleitung ist für den Standardinput 0< oder verkürzt <.
    Für den Standardoutput 1> oder verkürzt >.
    Für alle anderen Datenkanäle ist die Angabe der Kanalnummer zwingend. Da ohne weiteres noch weitere Datenkanäle definiert werden können, lautet die Notation für Eingabekanäle allgemein:
    n<
    und für Ausgabekanäle
    n>
    , wobei n die jeweilige Kanalnummer angibt.
    Das auf die Umleitungsoperatoren folgende Wort wird durch die shell expandiert. Das Ergebnis der Expansion wird als Name einer Umleitungsdatei interpretiert. Wird in mehr als ein Wort expandiert, so erzeugt die bash eine Fehlermeldung. Die bash wird versuchen, diese Datei zu öffnen oder zu erzeugen. Schlägt das Öffnen oder Erzeugen einer Umleitungsdatei fehl, so wird durch die bash eine Fehlermeldung erzeugt. Das Kommando wird nicht ausgeführt.
    Die Reihenfolge der Umleitungsdefinitionen hat ebenfalls Auswirkungen auf die Art der Umleitung selbst. Mit dem Kommandoaufruf.
    ls > dirlist 2>&1
    werden die Ausgaben von Standardout, Kanal 1 und Standarderr Kanal 2 in die Datei dirlist umgeleitet. Beim Kommandoaufruf:
    ls 2>&1 > dirlist
    wird nur eine Kopie von Standarderr Kanal 2 nach Standardout, Kanal 1 umgeleitet und in die Datei dirlist geschickt. Die Meldungen von Standarderr, Kanal 2 erscheinen dadurch weiterhin auf dem Bildschirm. Die bash verwaltet weiterhin spezielle (virtuelle) Dateien zur Verwendung in Umleitungen. Diese können der folgenden Tabelle entnommen werden:

    DateinameBedeutung
    /dev/fd/fdfd ist eine gültige Kanalnummer. Diese Spezialdatei ist eine Referenz auf den Filedescriptor fd, Kanal fd.
    /dev/stdinDiese Spezialdatei ist eine Referenz auf Standardin, Kanal 0.
    /dev/stdoutDiese Spezialdatei ist eine Referenz auf Standardout, Kanal 1.
    /dev/stderrDiese Spezialdatei ist eine Referenz auf Standarderr, Kanal 2.
    /dev/tcp/host/port

    Diese Spezialdatei ist eine Referenz auf einen TCP-Socket. Wenn host ein gütiger Hostname oder eine gültige IP-Adresse und port eine gültige Portnummer oder ein Service-Portname ist, so öffnet die bash eine entsprechende Netzwerkverbindung.

    /dev/udp/host/port

    Diese Spezialdatei ist eine Referenz auf einen UDP-Socket. Wenn host ein gütiger Hostname oder eine gültige IP-Adresse und port eine gültige Portnummer oder ein Service-Portname ist, so öffnet die bash eine entsprechende Netzwerkverbindung.

    /dev/null

    Diese Gerätedatei ist zwar keine Spezialdatei der bash, wird im Zusammenhang mit Umleitungen jedoch häufig genutzt. Alle an diese Gerätedatei gesendeten Datenströme werden vernichtet (Trash). Durch eine Umleitung nach /dev/null können also z.B. Ausgaben oder Fehlermeldungen unterdrückt werden.
    Durch das Kommando
    find / 2> /dev/null
    wird eine Ausgabeumleitung der Fehlermeldungen auf Standarderr, z.B. Meldungen über fehlende Zugriffsberechtigungen, nach /dev/null definiert, somit gelangen sie nicht mehr auf den Bildschirm.

    • Eingabeumleitung

      Eine Eingabeumleitung wird mit der Notation:
      [n]<word
      definiert. Der Ausdruck word muss nach der Expansion durch die bash den Namen einer Datei ergeben, die lesend geöffnet werden kann. Der Dateiinhalt kann dann über den Filedescriptor n auf kanal n gelesen werden. Ist n eine 0 (Null) oder wird keine Kanalnummer angegeben, so werden die Daten nach Standardin umgeleitet.

    • Ausgabeumleitung

      Eine Ausgabeumleitung wird mit der Notation:
      [n]>word
      definiert. Der Ausdruck word muss nach der Expansion durch die bash den Namen einer Datei ergeben, die schreibend geöffnet werden kann. Daten, die auf den Filedescriptor n auf Kanal n geschrieben werden, werden in die Datei umgeleitet. Der alte Inhalt der Datei wird überschrieben und geht verloren. Ist n eine 1 oder wird keine Kanalnummer angegeben, so werden die Daten von Standardout umgeleitet.
      Wurde beim Start der bash die noclobber-Option enabled, so erzeugt eine Umleitung mit dem Operator > einen Fehler, wenn die Umleitungsdatei eine reguläre Datei ist und bereits existiert. Soll eine Umleitung in die Datei trotzdem durchgeführt werden, so ist der Operator >¦ zu verwenden. Wurde die noclobber-Option disabled oder wird der Operator >¦ verwendet, so wird der alte Inhalt der Umleitungsdatei ohne Nachfrage oder Fehlermeldung überschrieben und geht dadurch verloren. Sollte die Umleitungsdatei noch nicht existieren, so wird die bash versuchen eine solche Datei anzulegen. Wenn das Anlegen der Datei fehlschlägt, so erzeugt die bash eine Fehlermeldung, das Kommando wird nicht ausgeführt.

    • anhängende Ausgabeumleitung

      Eine anhängende Ausgabeumleitung wird mit der Notation:
      [n]>>word
      definiert. Sie funktioniert im Wesentlichen genau so wie eine einfache Ausgabeumleitung. Wenn die Umleitungsdatei bereits existiert, so wird der Inhalt jedoch nicht überschrieben, sondern die umgeleiteten Daten werden an das Ende der Umleitungsdatei angehängt. Sollte die Umleitungsdatei noch nicht existieren, so wird die bash versuchen eine solche Datei anzulegen. Wenn das Anlegen der Datei fehlschlägt, so erzeugt die bash eine Fehlermeldung, das Kommando wird nicht ausgeführt.

    • Umleitung von Standardout und Standarderr in eine Datei

      Die Bash erlaubt es, die Datenströme von Standardout und Standarderr gemeinsam in eine Datei umzuleiten. Die Notation der Umleitung ist:
      &>word
      oder
      >&word
      Von den beiden Formen ist die erste vorzuziehen, sie sind aber beide äquivalent zur Notation:
      >word 2>&1

    • Here Dokumente

      Dieser Umleitungstyp veranlasst die bash einen Input direkt aus den aktuellen Sourcen zu lesen. Damit können innerhalb eines shell-Scriptes mehrere Zeilen z.B. direkt aus dem Scripttext nach Standardin umgeleitet werden. Die Notation für ein Here-Document hat folgende Notation:
      <<[-]word
        ....
        here-document
        ....
      delimiter
      Es werden alle Zeilen zwischen der Startzeile (<<[-]word) und dem abschliessenden delimiter gelesen und als Standardinput an ein Kommando gesendet. word und delimiter müssen absolut identisch sein. Die delimiter-Zeile darf keine weiteren (auch nicht sichtbaren) Zeichen außer dem abschliessenden <newline> enthalten. Für den Inhalt des Here-Dokumentes gelten folgende Regeln:
      Wenn word gequotet wird, dann wird keine Parameterexpansion, Kommandosubstitution, Arithmeticexpansion und Pfadnamenexpansion auf word angewendet. delimiter muss dann dem entquoteten Ergebnis von word entsprechen. Der Inhalt des Here-Dokumentes wird dann nicht expandiert. Ist word ungequotet, so werden auf die Zeilen des Here-Dokumentes die Parameterexpansion, Kommandosubstitution und Arithmeticexpansion angewendet. Ein gequotetes <newline> wird ignoriert, die Sonderzeichen \, $ und ` müssen mit dem backslash \ gequotet werden, um die Sonderbedeutung aufzuheben. If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line con­ taining delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

    • Here Strings

      Eine Variante des Here-Documents ist der Here-String der Form:
      <<<word
      word wird durch die shell expandiert und dann als Standardinput an ein Kommando gesendet.

    • Duplizieren eines Filedescriptors

      Der Umleitungsoperator:
      [n]<&word
      wird benutzt, um einen Input-Filedescriptor zu duplizieren. Wenn word in eine oder mehrere gültige Kanalnummern expandiert wird, so wird der Inhalt dieser Kanäle in den Kanal n kopiert. Sollte eine aus word expandierte Kanalnummer kein gültiger Input-Kanal sein, so wird die Umleitung mit einem Fehler abgebrochen. Durch die Notation: [n]<&-
      wird der Kanal n geschlossen. Wird n nicht explizit angegeben, so beziehen sich die Umlenkungen auf den Standardinput-Kanal 0.
      Der Operator:
      [n]>&word
      wird in ähnlicher Weise benutzt, um einen Output-Kanal zu duplizieren. Wenn n nicht explizit angegeben wird, so beziehen sich die Umlenkungen auf den Standardoutput-Kanal 1. Sollte eine aus word expandierte Kanalnummer kein gültiger Output-Kanal sein, so wird die Umleitung mit einem Fehler abgebrochen.
      Eine Besonderheit ist die Notation:
      >&
      durch die der Standardoutput-Kanal 1 und Standarderror-Kanal 2 gemeinsam umgeleitet werden.

    • Filedescriptor umbenennen

      Der Umleitungsoperator:
      [n]<&digit-
      dupliziert den Kanal digit in den Kanal n um. Wenn n nicht angegeben wird, so bezieht sich die Operation auf den Standardinput-Kanal 0. Nach der Duplizierung wird der Kanal digit geschlossen.
      Ähnlich verhält es sich mit dem Umleitungsoperator:
      [n]>&digit-
      der Kanal digit wird in den Kanal n dupliziert. Wenn n nicht angegeben wird, so bezieht sich die Operation auf den Standardoutput-Kanal 1.

    • R/W Filedescriptor öffnen

      Der Umleitungsoperator:
      [n]<>word
      bewirkt, die Öffnung des Filedescriptors n mit lesendem und schreibendem Zugriff auf eine Datei, deren Name aus word expandiert wird. Wenn n nicht angegeben wird, so bezieht sich die Operation auf den Standardinput-Kanal 0. Sollte die Datei nicht existieren, so wird versucht sie anzulegen. Sollte das fehlschlagen, so wird die Umleitung mit einer Fehlermeldung abgebrochen.

  19. ALIASES

    Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands (see SHELL BUILTIN COMMANDS below). The first word of each command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The alias name and the replacement text may con­ tain any valid shell input, including the metacharacters listed above, with the exception that the alias name may not contain =. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to ls -F, for instance, and bash does not try to recursively expand the replacement text. If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion. Aliases are created and listed with the alias command, and removed with the unalias command. There is no mechanism for using arguments in the replace­ ment text. If arguments are needed, a shell function should be used (see FUNCTIONS below). Aliases are not expanded when the shell is not interac­ tive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below). The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one com­ plete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias defi­ nition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands. For almost every purpose, aliases are superseded by shell functions.
  20. FUNCTIONS

    Eine shell-Funktion ist eine in der shell definierte Abfolge von Kommandos, die unter einem Namen aufgerufen werden kann. Der Funktionsname wird wie ein shellkommando benutzt. Wird er aufgerufen, so wird die Kommandoliste die in der Funktionsdefinition festgelegt wurde, ausgeführt. Die Funktion wird innerhalb Shell ausgeführt, es wird also kein eigener Prozess oder eine eigene Subshell gestartet. Damit ist die Ausführung einer Shellfunktion einem Aufruf eines Shellscriptes vorzuziehen. When a function is executed, the arguments to the function become the positional parameters during its execution. The special parameter # is updated to reflect the change. Positional parameter 0 is unchanged. The FUNCNAME variable is set to the name of the function while the function is executing. All other aspects of the shell execution environment are identical between a func­ tion and its caller with the exception that the DEBUG trap (see the description of the trap builtin under SHELL BUILTIN COMMANDS below) is not inherited unless the func­ tion has been given the trace attribute (see the descrip­ tion of the declare builtin below). Variables local to the function may be declared with the local builtin command. Ordinarily, variables and their values are shared between the function and its caller. If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. When a function com­ pletes, the values of the positional parameters and the special parameter # are restored to the values they had prior to the function's execution. Function names and definitions may be listed with the -f option to the declare or typeset builtin commands. The -F option to declare or typeset will list the function names only. Functions may be exported so that subshells auto­ matically have them defined with the -f option to the export builtin. Functions may be recursive. No limit is imposed on the number of recursive calls.

  21. Arithmetische Berechnungen (ARITHMETIC EVALUATION)

    Die bash erlaubt die Berechnung arithmetischer Ausdrücke unter verschiedenen Umständen. Einaml durch die Verwendung des internenshell-Kommandos let und zum anderen durch die Arithmetic Expansion. Die Berechnung wird mit Integerzahlen durchgeführt. Es wird kein Test auf Zahlenbereichsüberschreitung durchgeführt. Die Division durch 0 führt zur Auslösung eines Signals (SIGFPE). The operators and their precedence and associativity are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence. Folgende Operatoren stehen in der bash zur Verfügung. Die Operatoren sind absteigend nach ihrer Wertigkeit aufgelistet:
    OperatorBedeutung
    id++ id--Variablen postincrement postdecrement
    ++id --idVariablen preincrement predecrement
    + -positives Vorzeichen, negatives Vorzeichen
    ! ~logische Negation, bitweise Negation
    **Exponentfunktion
    * / %Multiplikation, Division, Modulo
    + -Addition, Subtraktion
    << >>bitweises Linksschieben, bitweises Rechtsschieben
    <= >= < >kleiner und gleich, größer und gleich, kleiner, größer
    == !=gleich, ungleich
    &bitweises UND
    ^bitweises Exclusiv-ODER
    ¦bitweises ODER
    &&logisches UND
    ¦¦logisches ODER
    expr?expr:exprabhängige Berechnung
    = *= /= %= += -= <<= >>= &= ^= ¦=komplexe Zuweisungsoperatoren
    expr1 , expr2Komma

    shell-Variablen sind als Operanden erlaubt. Vor der Berechnung wird die Parameterexpansion durchgeführt. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is referenced. A shell variable need not have its integer attribute turned on to be used in an expression. Konstanten, die mit einer führenden Null beginnen, werden als oktale Integerzahlen interpretiert. Konstanten, die mit 0x beginnen, werden als hexadezimale Inegerzahlen interpretiert. Konstanten n in der Form [base#]n, werden als Zahlen mit der Zahlenbasis interpretiert. base ist eine Dezimalzahl zwischen 2 und 64. Wenn [base#] nicht angegeben wird, so ist die Zahlenbasis 10. Ziffern größer als 9 werden mit Kleinbuchstaben, Großbuchstaben und @ und _ notiert. interpretiert. Bei Zahlenbasen kleiner 36 bilden die Klein- und Großbuchstaben die Ziffernwerte 10 bis 35 ab. Subexpressions in parentheses are evaluated first and may override the precedence rules above.

  22. Vergleichsoperatoren (CONDITIONAL EXPRESSIONS)

    Vergleichs-Operatoren werden in den Komandos [[, test und [ verwendet um Dateiatribute zu testen oder arithmetische Werte oder Zeichenketten miteinander zu vergleichen und zu testen. Die Operatoren sind entweder unär oder binär.
    Wenn eines der Dateiargumente eines der Spezialfiles /dev/fd/n ist, dann wird der Filedeskriptor n getestet.
    Mit den Dateiargumenten /dev/stdin, /dev/stdout oder /dev/stderr werden die Filedeskriptoren 0,1 oder 2 getestet.

    OperatorBedeutung
    -a Dateiwahr, wenn die Datei existiert
    -b Dateiwahr, wenn die Datei existiert und eine blockorientierte Gerätedatei ist (z.B. /dev/hda1)
    -c Dateiwahr, wenn die Datei existiert und eine zeichenorientierte Gerätedatei ist (z.B. /dev/ttyS0)
    -d Dateiwahr, wenn die Datei existiert und ein Verzeichnis ist
    -e Dateiwahr, wenn die Datei existiert
    -f Dateiwahr, wenn die Datei existiert und eine normale Datei ist
    -g Dateiwahr, wenn die Datei existiert und das Set-Group-ID-Bit gesetzt ist
    -h Dateiwahr, wenn die Datei existiert und ein symbolischer Link ist
    -k Dateiwahr, wenn die Datei existiert und das Sticky-Bit gesetzt ist
    -p Dateiwahr, wenn die Datei existiert und eine Named-Pipe ist
    -r Dateiwahr, wenn die Datei existiert und lesbar ist
    -s Dateiwahr, wenn die Datei existiert und mindestens ein Zeichen enthält
    -t Kanalnummerwahr, wenn die Kanalnummer geöffnet und mit einem Terminal verknüpft ist.
    -u Dateiwahr, wenn die Datei existiert und das Set-User-ID-Bit gesetzt ist
    -w Dateiwahr, wenn die Datei existiert und schreibbar ist
    -x Dateiwahr, wenn die Datei existiert und ausführbar ist
    -O Dateiwahr, wenn die Datei existiert und dem effektiven User gehört
    -G Dateiwahr, wenn die Datei existiert und der effektiven Gruppe gehört
    -L Dateiwahr, wenn die Datei existiert und ein symbolischer Link ist
    -S Dateiwahr, wenn die Datei existiert und ein Socket ist
    -N Dateiwahr, wenn die Datei existiert und seit dem letzten Lesezugriff verändert wurde
    file1 -nt file2wahr, wenn die Datei file1 ein neueres Modifikationsdatum als file2 hat, oder wenn file2 existiert und file1 nicht
    file1 -ot file2wahr, wenn die Datei file1 ein älteres Modifikationsdatum als file2 hat, oder wenn file1 existiert und file2 nicht
    file1 -et file2wahr, wenn die Dateien file1 und file2 eine Referenz auf die selbe Inodenummer auf dem gleichen Device sind
    -n Zeichenkettewahr, wenn die Zeichenkette mindestens ein beliebiges Zeichen (auch Leerzeichen) enthält
    -o optnamewahr, wenn die shell-Option optname gesetzt ist
    -z Zeichenkettewahr, wenn die Zeichenkette ein NULL-String ist, dh die Länge 0 besitzt
    Zeichenkette1 == Zeichenkette2wahr, wenn die Zeichenketten identisch sind
    Zeichenkette1 != Zeichenkette2wahr, wenn die Zeichenketten nicht identisch sind
    Zeichenkette1 < Zeichenkette2wahr, wenn die Zeichenkette1 in alphabetischer Reihenfolge (entsprechend locale) vor Zeichenkette2 eingeordnet wird
    Zeichenkette1 > Zeichenkette2wahr, wenn die Zeichenkette1 in alphabetischer Reihenfolge (entsprechend locale) nach Zeichenkette2 eingeordnet wird
    Wert1 -eq Wert2wahr, wenn Wert1 und Wert2 gleich sind (equal)
    Wert1 -ne Wert2wahr, wenn Wert1 und Wert2 ungleich sind (no equal)
    Wert1 -lt Wert2wahr, wenn Wert1 kleiner als Wert2 ist (less then)
    Wert1 -gt Wert2wahr, wenn Wert1 größer als Wert2 ist (greater then)
    Wert1 -le Wert2wahr, wenn Wert1 kleiner oder gleich Wert2 ist (less equal)
    Wert1 -ge Wert2wahr, wenn Wert1 größer oder gleich Wert2 ist (greater equal)
  23. SIMPLE COMMAND EXPANSION

    When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right. 1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing. 2. The words that are not variable assignments or redirections are expanded. If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments. 3. Redirections are performed as described above under REDIRECTION. 4. The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the vari­ able. If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status. If no command name results, redirections are performed, but do not affect the current shell environment. A redi­ rection error causes the command to exit with a non-zero status. If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command sub­ stitution, the exit status of the command is the exit sta­ tus of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero.
  24. COMMAND EXECUTION

    After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken. If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described above in FUNCTIONS. If the name does not match a function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked. If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each element of the PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full path­ names of executable files (see hash under SHELL BUILTIN COMMANDS below). A full search of the directories in PATH is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell prints an error message and returns an exit status of 127. If the search is successful, or if the command name con­ tains one or more slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the arguments given, if any. If this execution fails because the file is not in exe­ cutable format, and the file is not a directory, it is assumed to be a shell script, a file containing shell com­ mands. A subshell is spawned to execute it. This sub­ shell reinitializes itself, so that the effect is as if a new shell had been invoked to handle the script, with the exception that the locations of commands remembered by the parent (see hash below under SHELL BUILTIN COMMANDS) are retained by the child. If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the pro­ gram. The shell executes the specified interpreter on operating systems that do not handle this executable for­ mat themselves. The arguments to the interpreter consist of a single optional argument following the interpreter name on the first line of the program, followed by the name of the program, followed by the command arguments, if any.
  25. COMMAND EXECUTION ENVIRONMENT

    The shell has an execution environment, which consists of the following: · open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin · the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation · the file creation mode mask as set by umask or inherited from the shell's parent · current traps set by trap · shell parameters that are set by variable assign­ ment or with set or inherited from the shell's par­ ent in the environment · shell functions defined during execution or inher­ ited from the shell's parent in the environment · options enabled at invocation (either by default or with command-line arguments) or by set · options enabled by shopt · shell aliases defined with alias · various process IDs, including those of background jobs, the value of $$, and the value of $PPID When a simple command other than a builtin or shell func­ tion is to be executed, it is invoked in a separate execu­ tion environment that consists of the following. Unless otherwise noted, the values are inherited from the shell. · the shell's open files, plus any modifications and additions specified by redirections to the command · the current working directory · the file creation mode mask · shell variables marked for export, along with vari­ ables exported for the command, passed in the envi­ ronment · traps caught by the shell are reset to the values the inherited from the shell's parent, and traps ignored by the shell are ignored A command invoked in this separate environment cannot affect the shell's execution environment. Command substitution and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its par­ ent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell envi­ ronment. Changes made to the subshell environment cannot affect the shell's execution environment. If a command is followed by a & and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as mod­ ified by redirections.
  26. ENVIRONMENT

    When a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the form name=value. The shell provides several ways to manipulate the environ­ ment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for export to child processes. Executed com­ mands inherit the environment. The export and declare -x commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell's initial environment, whose values may be modified in the shell, less any pairs removed by the unset command, plus any additions via the export and declare -x commands. The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in PARAMETERS. These assignment statements affect only the environment seen by that command. If the -k option is set (see the set builtin command below), then all parameter assignments are placed in the environment for a command, not just those that precede the command name. When bash invokes an external command, the variable _ is set to the full file name of the command and passed to that command in its environment.
  27. EXIT STATUS

    Der exit-status gibt eine Information über die Ausführung des letzten Kommandos. Wenn das Kommando fehlerlos ausgeführt werden konnte, so ist der exit-status Null (entspricht True). Ein exit-status größer Null (entspricht False) zeigt einen Fehler an. Wurde ein Kommando durch ein Signal beendet, so wird der exit-status 128+N zurückgegeben, wobei N die Signalnummer ist. Wurde ein Kommando nicht gefunden, so ist der exit-status 127. Wurde ein Kommando gefunden, ist jedoch nicht ausführbar, so ist der exit-status 126.
    Wenn während der Expansion oder der Ein-/Ausgabeumlenkung ein Fehler aufgetreten ist, wird ebenfalls ein exit-status größer Null zurückgegeben. Die internen shell-Kommandos geben ebenfalls den exit-status Null zurück, wenn sie korrekt ausgeführt wurden. Bei einem Fehler wird ein exit-status größer Null zurück gegeben. Alle internen shell-Kommandos geben den exit-status 2 zurück, wenn sie fehlerhaft benutzt wurden zurück. Die bash selbst gibt als exit-status den exit-status des letzten Kommandos zurück, dass sie ausgeführt hat. Der exit-status des zuletzt synchron ausgeführten Kommandos der shell kann aus dem Spezialparameter $? ausgelesen werden.
  28. SIGNALS

    When bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not kill an interac­ tive shell), and SIGINT is caught and handled (so that the wait builtin is interruptible). In all cases, bash ignores SIGQUIT. If job control is in effect, bash ignores SIGTTIN, SIGTTOU, and SIGTSTP. Synchronous jobs started by bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT as well. Commands run as a result of command substitution ignore the keyboard-gener­ ated job control signals SIGTTIN, SIGTTOU, and SIGTSTP. The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIG­ CONT to ensure that they receive the SIGHUP. To prevent the shell from sending the signal to a particular job, it should be removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to not receive SIGHUP using disown -h. If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an interactive login shell exits. When bash receives a signal for which a trap has been set while waiting for a command to complete, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.
  29. JOB CONTROL

    Job control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later point. A user typically employs this facility via an interactive interface sup­ plied jointly by the system's terminal driver and bash. The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs command. When bash starts a job asyn­ chronously (in the background), it prints a line that looks like: [1] 25647 indicating that this job is job number 1 and that the pro­ cess ID of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control. To facilitate the implementation of the user interface to job control, the operating system maintains the notion of a current terminal process group ID. Members of this pro­ cess group (processes whose process group ID is equal to the current terminal process group ID) receive keyboard- generated signals such as SIGINT. These processes are said to be in the foreground. Background processes are those whose process group ID differs from the terminal's; such processes are immune to keyboard-generated signals. Only foreground processes are allowed to read from or write to the terminal. Background processes which attempt to read from (write to) the terminal are sent a SIGTTIN (SIGTTOU) signal by the terminal driver, which, unless caught, suspends the process. If the operating system on which bash is running supports job control, bash contains facilities to use it. Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. Typing the delayed suspend char­ acter (typically ^Y, Control-Y) causes the process to be stopped when it attempts to read input from the terminal, and control to be returned to bash. The user may then manipulate the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be dis­ carded. There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a sub­ string that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. Simply naming a job can be used to bring it into the fore­ ground: %1 is a synonym for ``fg %1'', bringing job 1 from the background into the foreground. Similarly, ``%1 &'' resumes job 1 in the background, equivalent to ``bg %1''. The shell learns immediately whenever a job changes state. Normally, bash waits until it is about to print a prompt before reporting changes in a job's status so as to not interrupt any other output. If the -b option to the set builtin command is enabled, bash reports such changes immediately. Any trap on SIGCHLD is executed for each child that exits. If an attempt to exit bash is made while jobs are stopped, the shell prints a warning message. The jobs command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, the shell does not print another warning, and the stopped jobs are terminated.
  30. PROMPTING

    Die interaktiven bash verwendet verschiedene Promptsymbole, auf die über die shell-Variablen PS1, PS2 und PS3 Einfluss genommen werden kann. Der Prompt PS1 wird angezeigt, wenn die bash bereit ist, Kommandos entgegenzunehmen. Der Prompt PS2 wird angezeigt, wenn weitere Eingaben zur Vervollständigung des aktuellen Kommandos nötig sind. Die bash erlaubt es, die Promptmeldungen den eigenen Bedürfnissen anzupassen. Dazu können eine Reihe von backslash-escape-Sequenzen verwendet werden, die eine besondere Bedeutung besitzen.
    EscapesequenzBedeutung
    \abell, Glocke
    \dSystemdatum im Format Wochentag Monat Datum (Tue May 26)
    \D{format}frei formatierbares Datum, Formatierungssymbole siehe man 3 strftime
    \eEscape-Zeichen (033) zur Terminalsteuerung
    \hHostname
    \HFQ-Hostname
    \jAnzahl der Jobs in der shell
    \lTerminalname
    \nnewline, Zeilenschaltung
    \rcarriage return, Wagenrücklauf, Zeilenanfang
    \sName der shell ($0)
    \tSystemzeit im 24-Stunden-Format HH:MM:SS
    \TSystemzeit im 12-Stunden-Format HH:MM:SS
    \@Systemzeit im 12-Stunden-Format AM/PM
    \ASystemzeit im 24-Stunden-Format HH:MM
    \uUsername des angemeldeten Benutzers
    \vbash-Versionsnummer
    \Vbash-Versionsnummer und Release
    \wArbeitsverzeichnis
    \Wvollständiger Name des Arbeitsverzeichnisses
    \!the history number of this command
    \#the command number of this command
    \$wenn root angemeldet ist, so wird ein #-Zeichen zurückgegeben, ansonsten $
    \nnnZeichen mit dem octalen Zeichencode nnn
    \\backslash
    \[Einleitung einer Escape-Sequenz
    \]Abschluß einer Escape-Sequenz
    The command number and the history number are usually dif­ ferent: the history number of a command is its position in the history list, which may include commands restored from the history file (see HISTORY below), while the command number is the position in the sequence of commands exe­ cuted during the current shell session. After the string is decoded, it is expanded via parameter expansion, com­ mand substitution, arithmetic expansion, and quote removal, subject to the value of the promptvars shell option (see the description of the shopt command under SHELL BUILTIN COMMANDS below).

  31. READLINE

    This is the library that handles reading input when using an interactive shell, unless the --noediting option is given at shell invocation. By default, the line editing commands are similar to those of emacs. A vi-style line editing interface is also available. To turn off line editing after the shell is running, use the +o emacs or +o vi options to the set builtin (see SHELL BUILTIN COMMANDS below). Readline Notation In this section, the emacs-style notation is used to denote keystrokes. Control keys are denoted by C-key, e.g., C-n means Control-N. Similarly, meta keys are denoted by M-key, so M-x means Meta-X. (On keyboards without a meta key, M-x means ESC x, i.e., press the Escape key then the x key. This makes ESC the meta pre­ fix. The combination M-C-x means ESC-Control-x, or press the Escape key then hold the Control key while pressing the x key.) Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of the argument that is significant. Passing a negative argument to a command that acts in the forward direction (e.g., kill-line) causes that command to act in a backward direction. Commands whose behavior with argu­ ments deviates from this are noted below. When a command is described as killing text, the text deleted is saved for possible future retrieval (yanking). The killed text is saved in a kill ring. Consecutive kills cause the text to be accumulated into one unit, which can be yanked all at once. Commands which do not kill text separate the chunks of text on the kill ring. Readline Initialization Readline is customized by putting commands in an initial­ ization file (the inputrc file). The name of this file is taken from the value of the INPUTRC variable. If that variable is unset, the default is ~/.inputrc. When a pro­ gram which uses the readline library starts up, the ini­ tialization file is read, and the key bindings and vari­ ables are set. There are only a few basic constructs allowed in the readline initialization file. Blank lines are ignored. Lines beginning with a # are comments. Lines beginning with a $ indicate conditional constructs. Other lines denote key bindings and variable settings. The default key-bindings may be changed with an inputrc file. Other programs that use this library may add their own commands and bindings. For example, placing M-Control-u: universal-argument or C-Meta-u: universal-argument into the inputrc would make M-C-u execute the readline command universal-argument. The following symbolic character names are recognized: RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and TAB. In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed (a macro). Readline Key Bindings The syntax for controlling key bindings in the inputrc file is simple. All that is required is the name of the command or the text of a macro and a key sequence to which it should be bound. The name may be specified in one of two ways: as a symbolic key name, possibly with Meta- or Control- prefixes, or as a key sequence. When using the form keyname:function-name or macro, key­ name is the name of a key spelled out in English. For example: Control-u: universal-argument Meta-Rubout: backward-kill-word Control-o: "> output" In the above example, C-u is bound to the function univer­ sal-argument, M-DEL is bound to the function back­ ward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert the text ``> output'' into the line). In the second form, "keyseq":function-name or macro, key­ seq differs from keyname above in that strings denoting an entire key sequence may be specified by placing the sequence within double quotes. Some GNU Emacs style key escapes can be used, as in the following example, but the symbolic character names are not recognized. "\C-u": universal-argument "\C-x\C-r": re-read-init-file "\e[11~": "Function Key 1" In this example, C-u is again bound to the function uni­ versal-argument. C-x C-r is bound to the function re-read-init-file, and ESC [ 1 1 ~ is bound to insert the text ``Function Key 1''. The full set of GNU Emacs style escape sequences is \C- control prefix \M- meta prefix \e an escape character \\ backslash \" literal " \' literal ' In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available: \a alert (bell) \b backspace \d delete \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Back­ slash will quote any other character in the macro text, including " and '. Bash allows the current readline key bindings to be dis­ played or modified with the bind builtin command. The editing mode may be switched during interactive use by using the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). Readline Variables Readline has variables that can be used to further cus­ tomize its behavior. A variable may be set in the inputrc file with a statement of the form set variable-name value Except where noted, readline variables can take the values On or Off. The variables and their default values are: bell-style (audible) Controls what happens when readline wants to ring the terminal bell. If set to none, readline never rings the bell. If set to visible, readline uses a visible bell if one is available. If set to audi­ ble, readline attempts to ring the terminal's bell. comment-begin (``#'') The string that is inserted when the readline insert-comment command is executed. This command is bound to M-# in emacs mode and to # in vi com­ mand mode. completion-ignore-case (Off) If set to On, readline performs filename matching and completion in a case-insensitive fashion. completion-query-items (100) This determines when the user is queried about viewing the number of possible completions gener­ ated by the possible-completions command. It may be set to any integer value greater than or equal to zero. If the number of possible completions is greater than or equal to the value of this vari­ able, the user is asked whether or not he wishes to view them; otherwise they are simply listed on the terminal. convert-meta (On) If set to On, readline will convert characters with the eighth bit set to an ASCII key sequence by stripping the eighth bit and prefixing an escape character (in effect, using escape as the meta pre­ fix). disable-completion (Off) If set to On, readline will inhibit word comple­ tion. Completion characters will be inserted into the line as if they had been mapped to self-insert. editing-mode (emacs) Controls whether readline begins with a set of key bindings similar to emacs or vi. editing-mode can be set to either emacs or vi. enable-keypad (Off) When set to On, readline will try to enable the application keypad when it is called. Some systems need this to enable the arrow keys. expand-tilde (Off) If set to on, tilde expansion is performed when readline attempts word completion. history-preserve-point If set to on, the history code attempts to place point at the same location on each history line retrived with previous-history or next-history. horizontal-scroll-mode (Off) When set to On, makes readline use a single line for display, scrolling the input horizontally on a single screen line when it becomes longer than the screen width rather than wrapping to a new line. input-meta (Off) If set to On, readline will enable eight-bit input (that is, it will not strip the high bit from the characters it reads), regardless of what the termi­ nal claims it can support. The name meta-flag is a synonym for this variable. isearch-terminators (``C-[C-J'') The string of characters that should terminate an incremental search without subsequently executing the character as a command. If this variable has not been given a value, the characters ESC and C-J will terminate an incremental search. keymap (emacs) Set the current readline keymap. The set of valid keymap names is emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. The default value is emacs; the value of editing-mode also affects the default keymap. mark-directories (On) If set to On, completed directory names have a slash appended. mark-modified-lines (Off) If set to On, history lines that have been modified are displayed with a preceding asterisk (*). mark-symlinked-directories (Off) If set to On, completed names which are symbolic links to directories have a slash appended (subject to the value of mark-directories). match-hidden-files (On) This variable, when set to On, causes readline to match files whose names begin with a `.' (hidden files) when performing filename completion, unless the leading `.' is supplied by the user in the filename to be completed. output-meta (Off) If set to On, readline will display characters with the eighth bit set directly rather than as a meta- prefixed escape sequence. page-completions (On) If set to On, readline uses an internal more-like pager to display a screenful of possible comple­ tions at a time. print-completions-horizontally (Off) If set to On, readline will display completions with matches sorted horizontally in alphabetical order, rather than down the screen. show-all-if-ambiguous (Off) This alters the default behavior of the completion functions. If set to on, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. visible-stats (Off) If set to On, a character denoting a file's type as reported by stat(2) is appended to the filename when listing possible completions. Readline Conditional Constructs Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be per­ formed as the result of tests. There are four parser directives used. $if The $if construct allows bindings to be made based on the editing mode, the terminal being used, or the application using readline. The text of the test extends to the end of the line; no characters are required to isolate it. mode The mode= form of the $if directive is used to test whether readline is in emacs or vi mode. This may be used in conjunction with the set keymap command, for instance, to set bindings in the emacs-standard and emacs-ctlx keymaps only if readline is starting out in emacs mode. term The term= form may be used to include termi­ nal-specific key bindings, perhaps to bind the key sequences output by the terminal's function keys. The word on the right side of the = is tested against the both full name of the terminal and the portion of the terminal name before the first -. This allows sun to match both sun and sun-cmd, for instance. application The application construct is used to include application-specific settings. Each program using the readline library sets the applica­ tion name, and an initialization file can test for a particular value. This could be used to bind key sequences to functions use­ ful for a specific program. For instance, the following command adds a key sequence that quotes the current or previous word in Bash: $if Bash # Quote the current or previous word "\C-xq": "\eb\"\ef\"" $endif $endif This command, as seen in the previous example, ter­ minates an $if command. $else Commands in this branch of the $if directive are executed if the test fails. $include This directive takes a single filename as an argu­ ment and reads commands and bindings from that file. For example, the following directive would read /etc/inputrc: $include /etc/inputrc Searching Readline provides commands for searching through the com­ mand history (see HISTORY below) for lines containing a specified string. There are two search modes: incremental and non-incremental. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable are used to ter­ minate an incremental search. If that variable has not been assigned a value the Escape and Control-J characters will terminate an incremental search. Control-G will abort an incremental search and restore the original line. When the search is terminated, the history entry contain­ ing the search string becomes the current line. To find other matching entries in the history list, type Control-S or Control-R as appropriate. This will search backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a readline command will terminate the search and execute that command. For instance, a newline will terminate the search and accept the line, thereby executing the command from the history list. Readline remembers the last incremental search string. If two Control-Rs are typed without any intervening charac­ ters defining a new search string, any remembered search string is used. Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line. Readline Command Names The following is a list of the names of the commands and the default key sequences to which they are bound. Com­ mand names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region. Commands for Moving beginning-of-line (C-a) Move to the start of the current line. end-of-line (C-e) Move to the end of the line. forward-char (C-f) Move forward a character. backward-char (C-b) Move back a character. forward-word (M-f) Move forward to the end of the next word. Words are composed of alphanumeric characters (letters and digits). backward-word (M-b) Move back to the start of the current or previous word. Words are composed of alphanumeric charac­ ters (letters and digits). clear-screen (C-l) Clear the screen leaving the current line at the top of the screen. With an argument, refresh the current line without clearing the screen. redraw-current-line Refresh the current line. Commands for Manipulating the History accept-line (Newline, Return) Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to the state of the HISTCONTROL variable. If the line is a modified history line, then restore the history line to its original state. previous-history (C-p) Fetch the previous command from the history list, moving back in the list. next-history (C-n) Fetch the next command from the history list, mov­ ing forward in the list. beginning-of-history (M-<) Move to the first line in the history. end-of-history (M->) Move to the end of the input history, i.e., the line currently being entered. reverse-search-history (C-r) Search backward starting at the current line and moving `up' through the history as necessary. This is an incremental search. forward-search-history (C-s) Search forward starting at the current line and moving `down' through the history as necessary. This is an incremental search. non-incremental-reverse-search-history (M-p) Search backward through the history starting at the current line using a non-incremental search for a string supplied by the user. non-incremental-forward-search-history (M-n) Search forward through the history using a non- incremental search for a string supplied by the user. history-search-forward Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. history-search-backward Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. yank-nth-arg (M-C-y) Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previ­ ous command begin with word 0). A negative argu­ ment inserts the nth word from the end of the pre­ vious command. yank-last-arg (M-., M-_) Insert the last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn. shell-expand-line (M-C-e) Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions. See HISTORY EXPANSION below for a description of history expansion. history-expand-line (M-^) Perform history expansion on the current line. See HISTORY EXPANSION below for a description of his­ tory expansion. magic-space Perform history expansion on the current line and insert a space. See HISTORY EXPANSION below for a description of history expansion. alias-expand-line Perform alias expansion on the current line. See ALIASES above for a description of alias expansion. history-and-alias-expand-line Perform history and alias expansion on the current line. insert-last-argument (M-., M-_) A synonym for yank-last-arg. operate-and-get-next (C-o) Accept the current line for execution and fetch the next line relative to the current line from the history for editing. Any argument is ignored. edit-and-execute-command (C-xC-e) Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $FCEDIT, $EDITOR, and emacs as the editor, in that order. Commands for Changing Text delete-char (C-d) Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return EOF. backward-delete-char (Rubout) Delete the character behind the cursor. When given a numeric argument, save the deleted text on the kill ring. forward-backward-delete-char Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. quoted-insert (C-q, C-v) Add the next character typed to the line verbatim. This is how to insert characters like C-q, for example. tab-insert (C-v TAB) Insert a tab character. self-insert (a, b, A, 1, !, ...) Insert the character typed. transpose-chars (C-t) Drag the character before point forward over the character at point, moving point forward as well. If point is at the end of the line, then this transposes the two characters before point. Nega­ tive arguments have no effect. transpose-words (M-t) Drag the word before point past the word after point, moving point over that word as well. If point is at the end of the line, this transposes the last two words on the line. upcase-word (M-u) Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move point. downcase-word (M-l) Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move point. capitalize-word (M-c) Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move point. overwrite-mode Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to readline() starts in insert mode. In over­ write mode, characters bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to back­ ward-delete-char replace the character before point with a space. By default, this command is unbound. Killing and Yanking kill-line (C-k) Kill the text from point to the end of the line. backward-kill-line (C-x Rubout) Kill backward to the beginning of the line. unix-line-discard (C-u) Kill backward from point to the beginning of the line. The killed text is saved on the kill-ring. kill-whole-line Kill all characters on the current line, no matter where point is. kill-word (M-d) Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as those used by for­ ward-word. backward-kill-word (M-Rubout) Kill the word behind point. Word boundaries are the same as those used by backward-word. unix-word-rubout (C-w) Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring. delete-horizontal-space (M-\) Delete all spaces and tabs around point. kill-region Kill the text in the current region. copy-region-as-kill Copy the text in the region to the kill buffer. copy-backward-word Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. copy-forward-word Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. yank (C-y) Yank the top of the kill ring into the buffer at point. yank-pop (M-y) Rotate the kill ring, and yank the new top. Only works following yank or yank-pop. Numeric Arguments digit-argument (M-0, M-1, ..., M--) Add this digit to the argument already accumulat­ ing, or start a new argument. M-- starts a nega­ tive argument. universal-argument This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again ends the numeric argument, but is otherwise ignored. As a special case, if this command is immediately fol­ lowed by a character that is neither a digit or minus sign, the argument count for the next command is multiplied by four. The argument count is ini­ tially one, so executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on. Completing complete (TAB) Attempt to perform completion on the text before point. Bash attempts completion treating the text as a variable (if the text begins with $), username (if the text begins with ~), hostname (if the text begins with @), or command (including aliases and functions) in turn. If none of these produces a match, filename completion is attempted. possible-completions (M-?) List the possible completions of the text before point. insert-completions (M-*) Insert all completions of the text before point that would have been generated by possible-comple­ tions. menu-complete Similar to complete, but replaces the word to be completed with a single match from the list of pos­ sible completions. Repeated execution of menu-com­ plete steps through the list of possible comple­ tions, inserting each match in turn. At the end of the list of completions, the bell is rung (subject to the setting of bell-style) and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default. delete-char-or-list Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible-completions. This command is unbound by default. complete-filename (M-/) Attempt filename completion on the text before point. possible-filename-completions (C-x /) List the possible completions of the text before point, treating it as a filename. complete-username (M-~) Attempt completion on the text before point, treat­ ing it as a username. possible-username-completions (C-x ~) List the possible completions of the text before point, treating it as a username. complete-variable (M-$) Attempt completion on the text before point, treat­ ing it as a shell variable. possible-variable-completions (C-x $) List the possible completions of the text before point, treating it as a shell variable. complete-hostname (M-@) Attempt completion on the text before point, treat­ ing it as a hostname. possible-hostname-completions (C-x @) List the possible completions of the text before point, treating it as a hostname. complete-command (M-!) Attempt completion on the text before point, treat­ ing it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order. possible-command-completions (C-x !) List the possible completions of the text before point, treating it as a command name. dynamic-complete-history (M-TAB) Attempt completion on the text before point, com­ paring the text against lines from the history list for possible completion matches. complete-into-braces (M-{) Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell (see Brace Expansion above). Keyboard Macros start-kbd-macro (C-x () Begin saving the characters typed into the current keyboard macro. end-kbd-macro (C-x )) Stop saving the characters typed into the current keyboard macro and store the definition. call-last-kbd-macro (C-x e) Re-execute the last keyboard macro defined, by mak­ ing the characters in the macro appear as if typed at the keyboard. Miscellaneous re-read-init-file (C-x C-r) Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there. abort (C-g) Abort the current editing command and ring the ter­ minal's bell (subject to the setting of bell-style). do-uppercase-version (M-a, M-b, M-x, ...) If the metafied character x is lowercase, run the command that is bound to the corresponding upper­ case character. prefix-meta (ESC) Metafy the next character typed. ESC f is equiva­ lent to Meta-f. undo (C-_, C-x C-u) Incremental undo, separately remembered for each line. revert-line (M-r) Undo all changes made to this line. This is like executing the undo command enough times to return the line to its initial state. tilde-expand (M-&) Perform tilde expansion on the current word. set-mark (C-@, M-<space>) Set the mark to the point. If a numeric argument is supplied, the mark is set to that position. exchange-point-and-mark (C-x C-x) Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark. character-search (C-]) A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences. character-search-backward (M-C-]) A character is read and point is moved to the pre­ vious occurrence of that character. A negative count searches for subsequent occurrences. insert-comment (M-#) Without a numeric argument, the value of the read­ line comment-begin variable is inserted at the beginning of the current line. If a numeric argu­ ment is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of comment-begin, the value is inserted, otherwise the characters in comment-begin are deleted from the beginning of the line. In either case, the line is accepted as if a newline had been typed. The default value of comment-begin causes this command to make the current line a shell comment. If a numeric argument causes the comment character to be removed, the line will be executed by the shell. glob-complete-word (M-g) The word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern is used to generate a list of matching file names for possible completions. glob-expand-word (C-x *) The word before point is treated as a pattern for pathname expansion, and the list of matching file names is inserted, replacing the word. If a numeric argument is supplied, an asterisk is appended before pathname expansion. glob-list-expansions (C-x g) The list of expansions that would have been gener­ ated by glob-expand-word is displayed, and the line is redrawn. If a numeric argument is supplied, an asterisk is appended before pathname expansion. dump-functions Print all of the functions and their key bindings to the readline output stream. If a numeric argu­ ment is supplied, the output is formatted in such a way that it can be made part of an inputrc file. dump-variables Print all of the settable readline variables and their values to the readline output stream. If a numeric argument is supplied, the output is format­ ted in such a way that it can be made part of an inputrc file. dump-macros Print all of the readline key sequences bound to macros and the strings they ouput. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. display-shell-version (C-x C-v) Display version information about the current instance of bash. Programmable Completion When word completion is attempted for an argument to a command for which a completion specification (a compspec) has been defined using the complete builtin (see SHELL BUILTIN COMMANDS below), the programmable completion facilities are invoked. First, the command name is identified. If a compspec has been defined for that command, the compspec is used to generate the list of possible completions for the word. If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash. Once a compspec has been found, it is used to generate the list of matching words. If a compspec is not found, the default bash completion as described above under Complet­ ing is performed. First, the actions specified by the compspec are used. Only matches which are prefixed by the word being com­ pleted are returned. When the -f or -d option is used for filename or directory name completion, the shell variable FIGNORE is used to filter the matches. Any completions specified by a filename expansion pattern to the -G option are generated next. The words generated by the pattern need not match the word being completed. The GLOBIGNORE shell variable is not used to filter the matches, but the FIGNORE variable is used. Next, the string specified as the argument to the -W option is considered. The string is first split using the characters in the IFS special variable as delimiters. Shell quoting is honored. Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and pathname expansion, as described above under EXPANSION. The results are split using the rules described above under Word Splitting. The results of the expansion are prefix-matched against the word being com­ pleted, and the matching words become the possible comple­ tions. After these matches have been generated, any shell func­ tion or command specified with the -F and -C options is invoked. When the command or function is invoked, the COMP_LINE and COMP_POINT variables are assigned values as described above under Shell Variables. If a shell func­ tion is being invoked, the COMP_WORDS and COMP_CWORD vari­ ables are also set. When the function or command is invoked, the first argument is the name of the command whose arguments are being completed, the second argument is the word being completed, and the third argument is the word preceding the word being completed on the current command line. No filtering of the generated completions against the word being completed is performed; the func­ tion or command has complete freedom in generating the matches. Any function specified with -F is invoked first. The function may use any of the shell facilities, including the compgen builtin described below, to generate the matches. It must put the possible completions in the COM­ PREPLY array variable. Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output. Backslash may be used to escape a new­ line, if necessary. After all of the possible completions are generated, any filter specified with the -X option is applied to the list. The filter is a pattern as used for pathname expan­ sion; a & in the pattern is replaced with the text of the word being completed. A literal & may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will be removed from the list. A leading ! negates the pattern; in this case any completion not matching the pattern will be removed. Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the result is returned to the readline comple­ tion code as the list of possible completions. If the previously-applied actions do not generate any matches, and the -o dirnames option was supplied to com­ plete when the compspec was defined, directory name com­ pletion is attempted. By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of pos­ sible completions. The default bash completions are not attempted, and the readline default of filename completion is disabled. If the -o default option was supplied to complete when the compspec was defined, readline's default completion will be performed if the compspec generates no matches. When a compspec indicates that directory name completion is desired, the programmable completion functions force readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories readline variable, regardless of the set­ ting of the mark-symlinked-directories readline variable.
  32. HISTORY

    When the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. The text of the last HISTSIZE commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expansion (see EXPANSION above) but after history expansion is per­ formed, subject to the values of the shell variables HISTIGNORE and HISTCONTROL. On startup, the history is initialized from the file named by the variable HISTFILE (default ~/.bash_history). The file named by the value of HISTFILE is truncated, if nec­ essary, to contain no more than the number of lines speci­ fied by the value of HISTFILESIZE. When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE. If the histappend shell option is enabled (see the description of shopt under SHELL BUILTIN COMMANDS below), the lines are appended to the history file, otherwise the history file is overwritten. If HISTFILE is unset, or if the history file is unwritable, the history is not saved. After saving the history, the history file is truncated to contain no more than HISTFILESIZE lines. If HISTFILESIZE is not set, no truncation is performed. The builtin command fc (see SHELL BUILTIN COMMANDS below) may be used to list or edit and re-execute a portion of the history list. The history builtin may be used to dis­ play or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that provide access to the history list. The shell allows control over which commands are saved on the history list. The HISTCONTROL and HISTIGNORE vari­ ables may be set to cause the shell to save only a subset of the commands entered. The cmdhist shell option, if enabled, causes the shell to attempt to save each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correct­ ness. The lithist shell option causes the shell to save the command with embedded newlines instead of semicolons. See the description of the shopt builtin below under SHELL BUILTIN COMMANDS for information on setting and unsetting shell options.
  33. HISTORY EXPANSION

    The shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntax features are available. This fea­ ture is enabled by default for interactive shells, and can be disabled using the +H option to the set builtin command (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the cur­ rent input line, or fix errors in previous commands quickly. History expansion is performed immediately after a com­ plete line is read, before the shell breaks it into words. It takes place in two parts. The first is to determine which line from the history list to use during substitu­ tion. The second is to select portions of that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line that are acted upon are words. Various modifiers are available to manipulate the selected words. The line is broken into words in the same fashion as when reading input, so that several metacharacter-separated words sur­ rounded by quotes are considered one word. History expan­ sions are introduced by the appearance of the history expansion character, which is ! by default. Only back­ slash (\) and single quotes can quote the history expan­ sion character. Several shell options settable with the shopt builtin may be used to tailor the behavior of history expansion. If the histverify shell option is enabled (see the descrip­ tion of the shopt builtin), and readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the readline editing buffer for further modification. If readline is being used, and the histreedit shell option is enabled, a failed history substitution will be reloaded into the readline editing buffer for correction. The -p option to the history builtin command may be used to see what a history expansion will do before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall. The shell allows control of the various characters used by the history expansion mechanism (see the description of histchars above under Shell Variables). Event Designators An event designator is a reference to a command line entry in the history list. ! Start a history substitution, except when followed by a blank, newline, = or (. !n Refer to command line n. !-n Refer to the current command line minus n. !! Refer to the previous command. This is a synonym for `!-1'. !string Refer to the most recent command starting with string. !?string[?] Refer to the most recent command containing string. The trailing ? may be omitted if string is followed immediately by a newline. ^string1^string2^ Quick substitution. Repeat the last command, replacing string1 with string2. Equivalent to ``!!:s/string1/string2/'' (see Modifiers below). !# The entire command line typed so far. Word Designators Word designators are used to select desired words from the event. A : separates the event specification from the word designator. It may be omitted if the word designator begins with a ^, $, *, -, or %. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces. 0 (zero) The zeroth word. For the shell, this is the com­ mand word. n The nth word. ^ The first argument. That is, word 1. $ The last argument. % The word matched by the most recent `?string?' search. x-y A range of words; `-y' abbreviates `0-y'. * All of the words but the zeroth. This is a synonym for `1-$'. It is not an error to use * if there is just one word in the event; the empty string is returned in that case. x* Abbreviates x-$. x- Abbreviates x-$ like x*, but omits the last word. If a word designator is supplied without an event specifi­ cation, the previous command is used as the event. Modifiers After the optional word designator, there may appear a sequence of one or more of the following modifiers, each preceded by a `:'. h Remove a trailing file name component, leaving only the head. t Remove all leading file name components, leaving the tail. r Remove a trailing suffix of the form .xxx, leaving the basename. e Remove all but the trailing suffix. p Print the new command but do not execute it. q Quote the substituted words, escaping further sub­ stitutions. x Quote the substituted words as with q, but break into words at blanks and newlines. s/old/new/ Substitute new for the first occurrence of old in the event line. Any delimiter can be used in place of /. The final delimiter is optional if it is the last character of the event line. The delimiter may be quoted in old and new with a single back­ slash. If & appears in new, it is replaced by old. A single backslash will quote the &. If old is null, it is set to the last old substituted, or, if no previous history substitutions took place, the last string in a !?string[?] search. & Repeat the previous substitution. g Cause changes to be applied over the entire event line. This is used in conjunction with `:s' (e.g., `:gs/old/new/') or `:&'. If used with `:s', any delimiter can be used in place of /, and the final delimiter is optional if it is the last character of the event line.
  34. Interne Shellkommandos (SHELL BUILTIN COMMANDS)

    Eine Reihe von Kommandos sind bereits in die bash integriert, sogenannte interne Shellbefehle (builtin). Diese Befehle werden direkt in der Shellumgebung ausgeführt, dh. es ist nicht erforderlich eine eigene Subshell zu starten wie bei externen Kommandos. Dadurch ist der Ressoursenverbrauch entsprechend kleiner und die Ausführungszeiten sind kurz. Deshalb sind interne Shellbefehle den externen Kommandos auf jeden Fall vorzuziehen.
    Befehl
      Bedeutung
    : [arguments]
     

    Nullkommando. Verlangt die Syntax einen Befehl und man will jedoch nichts ausführen, dann verwendet man :. Es wird keine Expansion der Argumente durchgeführt. Der Rückgabewert ist 0(Null).

    #
     

    Einleitung eines Kommentars. Alle Zeichen nach dem Kommandozeichen # auf einer Zeile werden als Kommentar interpretiert.

    . filename [arguments]
    source filename [arguments]
     

    Punktkommando. Die Kommandos aus der Datei filename werden gelesen und ausgeführt. Der Rückgabewert entspricht dem exit-status des zuletzt ausgeführten Kommandos. Wenn die Kommandos fehlerfrei ausgeführt wurden, ist der Rückgabewert 0(Null). Wurde die Datei filename nicht gefunden oder war nicht lesbar, wird ein Rückgabewert >0 übergeben. Die Kommandos werden in der Shellumgebung ausgeführt, der Dateiinhalt wird eingesourct. Wenn die Datei filename ohne Pfadangabe erfolgt, dann muß sie im Suchpfad PATH zu finden sein. Übergebene Argumente werden expandiert und in den Positionsparametern zur Verfügung gestellt. Wenn keine Argumente übergeben werden, so bleiben die Positionsparameter unverändert.

    alias [-p] [name[=value] ...]
     

    Mit dem alias-Kommando können Kürzel für Befehle definiert werden. Wird alias ohne Argumente oder mit der Option -p aufgerufen, so wird eine Liste der bereits definierten Aliase der Form name=wert nach Standardout ausgegeben.

    bg [jobspec]
     

    Einen gestoppten Prozess in den Hintergrund schicken.

    bind [-m keymap] [-lpsvPSV]
    bind [-m keymap] [-q function] [-u function] [-r keyseq]
    bind [-m keymap] -f filename
    bind [-m keymap] -x keyseq:shell-command
    bind [-m keymap] keyseq:function-name
    bind readline-command
     

    key-bindings. Tastenbelegung für Extrafunktionen der Kommandozeile festlegen.

    break [n]
     

    Eine for, while, until oder select-Schleife wird vorzeitig verlassen.

    builtin shell-builtin [arguments]
     

    Ein Builtin-Kommando ausführen. Damit kann erzwungen werden, dass ein internes Shellkommando ausgeführt wird, auch wenn es eine Funktion oder ein Alias mit dem gleichen Namen gibt. Der Rückgabewert ist >0, wenn das angegebene Kommando kein internes Shellkommando ist.

    cd [-L|-P] [dir]
     

    Arbeitsverzeichnis wechseln.
    Das aktuelle Arbeitsverzeichnis wird zu dir verändert. Wenn kein Verzeichnis angegeben wird, wechselt cd zu HOME.

    command [-pVv] command [arg ...]
     

    Führt das Kommando command aus, auch wenn es eine Shellfunktion mit gleichem Namen gibt. Nur interne Shellkommandos oder externe Kommandos im Suchpfad PATH können damit ausgeführt werden. Mit der Option -p wird der Defaultwert für PATH verwendet. Damit wird sichergestellt, das alle Standardutilities des System verwendet werden können. Mit den Optionen -v und -V können verschiedene Informationen (verbose) zu dem geforderten Kommando erzeugt werden. Der Rückgabewert ist dann 0, wenn das Kommando gefunden wurde und 1 wenn es nicht gefunden wurde. Ohne diese Optionen -v/-V wird der Rückgabewert 127 erzeugt, wenn das Kommando nicht gefunden wurde. Ansonsten wird der Rückgabewert des Kommandos selbst zurückgegeben.

    compgen [option] [word]
     

    complete [-abcdefgjksuv] [-o comp-option] [-A action] [-G globpat] [-W wordlist] [-P prefix] [-S suffix][-X filterpat] [-F function] [-C command] name [name ...]
    complete -pr [name ...]
     

    continue [n]
     

    Mit dem nächsten Schleifendurchlauf in while, until oder select fortfahren.

    declare [-afFirtx] [-p] [name[=value]]
    typeset [-afFirtx] [-p] [name[=value]]
     

    Variablen deklarieren.
    Mit diesen Kommandos können Variablen definiert werden und diesen können gleichzeitig Attribute zugewiesen werden. Wird das Kommando ohne Angabe eines Namen aufgerufen, so wird eine Liste aller Variablen und ihrer Werte angezeigt. Mit der Option -p werden zu den Variablen die entsprechenden Attribute angezeigt, zusätzliche Optionen werden dabei ignoriert. Die Option -F unterdrückt die Anzeige von Funktionen, nur der Funktionsname und die zugehörigen Attribute werden angezeigt. Diese Option schließt dieOption -f mit ein. Mit den folgenden Optionen kann die Ausgabe unterschiedlich gesteuert werden und es können den Variablen die entsprechenden Attribute zugeordnet werden.

    OptionBedeutung
    -aDer Name bezeichnet eine Arrayvariable
    -fDer Name bezeichnet eine Funktion
    -iDie Variable enthält einen Integerwert
    -rreadonly Der Inhalt ist nur lesbar
    -tTrace (nur für Funktionen)
    -xMark names for export to subsequent commands via the environment.
    dirs [-clpv] [+n] [-n]
     

    Ausgabe des Directorystacks der ehemaligen Arbeitsverzeichnisse.

    disown [-ar] [-h] [jobspec ...]
     

    echo [-neE] [arg ...]
     

    Ausgabe von Text auf Standardout.
    Mit diesem Kommando werden die durch Leerzeichen getrennten Argumente auf Standardout ausgegeben. Die Ausgabe wird durch ein <newline> abgeschlossen. Der Rückgabewert ist 0(Null). Mit der Option -n kann das <newline> am Ende der Ausgabe unterdrückt werden. Mit der Option -e wird die Interpretation von Escapesequenzen aktiviert. Diese Escapesequenzen werden durch einen backslash eingeleitet. Das folgende Zeichen legt die Funktion der Escapesequenz fest. Sollen mehrere Escapesequenzen verwendet werden, so ist jede einzelne durch ein backslash einzuleiten. Die Option -E schaltet die Interpretation der Escapesequenzen ab. Diese Option wird auf Systemen benötigt, bei denen die Interpretation defaultmäßig eingeschaltet ist. Dieses wird mit der Shelloption xpg_echo voreingestellt. Echo interpretiert -- nicht als das Ende der Optionsliste. Folgende Escapesequenzen werden interpretiert:

    escapeBedeutung
    \aalert (bell)
    \bbackspace
    \csuppress trailing newline
    \ean escape character
    \fform feed
    \nnew line
    \rcarriage return
    \thorizontal tab
    \vvertical tab
    \\backslash
    \0nnnZeichen in octaler Notation des Zeichencodes (0..3 stellig)
    \nnnZeichen in octaler Notation des Zeichencodes (1..3 stellig)
    \xHHZeichen in hexadezimaler Notation des Zeichencodes (1 oder 2 stellig)
    enable [-adnps] [-f filename] [name ...]
     

    Schaltet ein builtin-Kommando ab/an. Mit -n wird abgeschaltet.

    eval [arg ...]
     

    Argumente als Kommando ausführen.
    Die Argumente werden eingelesen und zu einem Kommando verbunden. Dieses wird durch die Shell eingelesen und ausgeführt. Der Rückgabewert von eval entspreicht dem Rückgabewert des ausgeführten Kommandos. Wird kein Argument an eval übergeben oder enthalten die Argumente alle einen Nullstring, so ist der Rückgabewert 0.

    exec [-cl] [-a name] [command [arguments]]
     

    Überlagerung der Shell durch ein neues Kommando.
    Mit diesem Kommando wird die Shell durch das Kommando command ersetzt. Dabei wird kein neuer Prozess gestartet. Die Argumente werden an das Kommando command übergeben.

    exit [n]
     

    Beendet die aktuelle Shell.
    Die Shell wird beendet. Wenn ein Parameter n (0..255) angegeben wird, so liefert die Shell diesen Wert als Rückgabewert an der übergeordneten Prozess. Wird exit ohne Parameter aufgerufen, so entspricht der Rückgabewert der Shell dem exit-status des letzten ausgeführten Kommandos. Eine Signalbehandlung (trap EXIT) wird noch ausgeführt bevor die Shell sich beendet.

    export [-fn] [name[=word]]
    ...
    export -p
     

    Exportiert Shell-Variablen in das Environment, womit diese den Subshells zur Verfügung stehen.
    Die Option -f wird verwendet, wenn name auf eine Funktion verweist. Wenn export ohne name oder mit der Option -p aufgerufen wird, so wird eine Liste aller exportierter Shell-Variablenangezeigt. export erzeugt einen Rückgabewert 0(Null) wenn es ohne Fehler ausgeführt wurde. Der Rückgabewert ist >0, wenn eine ungültige Option verwendet wurde oder mindestens einer der angegeben Namen kein Name einer Shell-Variable ist oder bei gesetzter Option -f ein ungültiger Funktionsname verwendet wurde.

    fc [-e ename] [-nlr] [first] [last]
    fc -s [pat=rep] [cmd]
     

    Zeigt die Befehls-History an oder führt bestimmte Befehle der History aus.

    fg [jobspec]
     

    getopts optstring name [args]
     

    hash [-lr] [-p filename] [-dt] [name]
     

    help [-s] [pattern]
     

    history [n]
    history -c
    history -d offset
    history -anrw [filename]
    history -p arg [arg ...]
    history -s arg [arg ...]
     

    jobs [-lnprs] [ jobspec ... ]
    jobs -x command [ args ... ]
     

    kill [-s sigspec | -n signum | -sigspec] [pid | jobspec]
    ...
    kill -l [sigspec | exit_status]
     

    let arg [arg ...]
     

    local [option] [name[=value] ...]
     

    logout
      Beendet die Login-Shell, Abmeldung.
    popd [-n] [+n] [-n]
     

    printf format [arguments]
     

    pushd [-n] [dir]
    pushd [-n] [+n] [-n]
     

    pwd [-LP]
     

    read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt][-n nchars] [-d delim] [name ...]
     

    read liest eine Zeile vom Standardinputkanal 0 (NUll) oder einem mit der Option -u angegebenen Filedeskriptor. Das erste gelesene Wort wird in der ersten mit [name] angegebenen Variable gespeichert. Das zweite Wort in der zweiten Variable usw. usf. Die Trennzeichen werden dabei entfernt. Wenn mehr Worte eingegeben werden, als Variablen angegeben sind, so speichert read den Rest der Eingabe mit den Trennzeichen in der letzten Variablen ab. Wurden weniger Worte eingegeben, als Variablen angegeben sind, so bleiben die überzähligen Variablen leer (Leerstring). Als Trennzeichen werden die Zeichen der Shellvariable IFS akzeptiert. Quotungen können mit einem backslash vorgenommen werden. Mit \<newline> kann die Eingabe auf der folgenden Zeile fortgesetzt werden. read kennt folgende Optionen:

    OptionBedeutung
    -a aname

    aname ist der Name eines Arrays, in dem die einzelnen Worte der Eingabe fortlaufend ab dem Index 0 (Null) abgelegt werden. Auf das Array wird vorher ein unset angewendet, d.h. alle vorher im Array abgelegten Werte gehen verloren. Bei Verwendung dieser Option werden alle mit [name] angegebenen Variablen ignoriert.

    -d delim

    Das Zeichen delim wird als Terminator für die Eingabezeile interpretiert. Beim ersten Auftreten dieses Zeichens beendet read seine Arbeit. Ohne Angabe dieser Option ist <newline> der Delimiter.

    -e

    Wenn der Standardinput mit einem Terminal verbunden ist, so werden die Daten mit readline gelesen.

    -n nchars

    nchars gibt die Anzahl der Zeichen an, die von read maximal gelesen werden sollen. Ist die Anzahl erreicht, so beendet read seine Arbeit. Ohne diese Option wird immer die komplette Zeile bis zum Delimiter gelesen.

    -p prompt

    Wenn der Eingabekanal mit einem Terminal verbunden ist, so gibt read vor dem Lesen der Eingabe prompt ohne Zeilenschaltung über der Standarderrorkanal 2 an das Terminal aus.

    -r

    Der backslash verliert seine Sonderbedeutung, er wird behandelt wie ein normales Zeichen. Auch eine Fortsetzung der Eingabe auf der Folgezeile mit \<newline> ist nicht möglich.

    -s

    Silent mode. Wenn die Eingabe über ein Terminal erfolgt, so wird echo abgeschaltet. Die eingegebenen Zeichen erscheinen nicht im Terminal (z.B. bei Passworteingaben).

    -t timeout

    read wartet die angegebene Anzahl von Sekunden auf eine vollständige Eingabe. Wurde die Eingabe nicht innerhalb der vorgegebenen Zeitspanne abgeschlossen, so beendet read seine Arbeit und meldet über der exit-status einen Fehler. Diese Option wird nur ausgewertet, wenn die Daten von einem Terminal oder einer Pipe gelesen werden.

    -u fdFP

    Mit der Option -u kann festgelegt werden, das die Daten nicht vom Standardeingabekanal 0 (Null) sondern aus dem Filedescriptor fd gelesen werden sollen.

    Wurden read keine Variablen oder ein Array zum ablegen der gelesenen Daten übergeben, so speichert es diese in der Shellvariable REPLY ab. Der exit-Code von read ist 0 (wahr), außer es wurde ein EOF (end-of-file) erkannt, ein read-Timeout ausgelöst oder ein fehlerhafter Filedeskriptor, je nach den Vorgaben der Option -u, festgestellt.

    readonly [-apf] [name ...]
     

    return [n]
     

    set [--abefhkmnptuvxBCHP] [-o option] [arg ...]
     

    shift [n]
     

    shopt [-pqsu] [-o] [optname ...]
     

    suspend [-f]
     

    test expr [ expr ]
     

    Das Kommando test prüft eine oder mehrere Bedingungen expr und gibt als Ergebnis der Prüfung den exit-Code 0 für wahr und den exit-Code 1 für falsch zurück. Die Bedingungen können durch logische Operatoren miteinander verknüpft werden. In der folgenden Liste sind diese Operatoren nach ihrem Rang aufgelistet.

    ! expr Wahr, wenn die Bedingung expr falsch ist (Negation)
    ( expr ) Gibt den Wahrheitswert von expr zurück. Die Klammern werden benutzt, um verkettete Bedingungen abweichend von dem Vorrang der logischen Oberationen zu gruppieren.
    expr1 -a expr2 Ist wahr, wenn Bedingung expr1 und Bedingung expr2 wahr sind (logisches UND/AND)
    expr1 -o expr2 Ist wahr, wenn Bedingung expr1 oder Bedingung expr2 oder beide wahr sind (logisches ODER/OR)
    times
     

    trap [-lp] [arg] [sigspec ...]
     

    type [-aftpP] name [name ...]
     

    ulimit [-SHacdflmnpstuv [limit]]
     

    umask [-p] [-S] [mode]
     

    unalias [-a] [name ...]
     

    unset [-fv] [name ...]
     

    wait [n]
     

  35. RESTRICTED SHELL

    If bash is started with the name rbash, or the -r option is supplied at invocation, the shell becomes restricted. A restricted shell is used to set up an environment more controlled than the standard shell. It behaves identi­ cally to bash with the exception that the following are disallowed or not performed: · changing directories with cd · setting or unsetting the values of SHELL, PATH, ENV, or BASH_ENV · specifying command names containing / · specifying a file name containing a / as an argu­ ment to the . builtin command · Specifying a filename containing a slash as an argument to the -p option to the hash builtin com­ mand · importing function definitions from the shell envi­ ronment at startup · parsing the value of SHELLOPTS from the shell envi­ ronment at startup · redirecting output using the >, >|, <>, >&, &>, and >> redirection operators · using the exec builtin command to replace the shell with another command · adding or deleting builtin commands with the -f and -d options to the enable builtin command · Using the enable builtin command to enable disabled shell builtins · specifying the -p option to the command builtin command · turning off restricted mode with set +r or set +o restricted. These restrictions are enforced after any startup files are read. When a command that is found to be a shell script is exe­ cuted (see COMMAND EXECUTION above), rbash turns off any restrictions in the shell spawned to execute the script.
  36. FILES

    DateiBedeutung
    /bin/bashDas bash-binary, eine ausführbare Datei
    /etc/profile

    Systemweite Initialisierungsdatei für die bash. Diese Datei wird von einer interaktiven Login-Shell abgearbeitet und setzt systemweite, vom User im allgemeinen nicht veränderbare Einstellungen.

    ~/.profile

    Diese Datei ist die lokale benutzerdefinierte Konfigurationsdatei für eine interaktive Login-Shell, die der User seinen eigenen Bedürfnissen anpassen kann. Sie wird nur verwendet, wenn keine ~/.bash_profile oder ~/.bash_login existiert.

    ~/.bash_profile

    Diese Datei ist die lokale benutzerdefinierte Konfigurationsdatei für eine interaktive Login-Shell, die der User seinen eigenen Bedürfnissen anpassen kann.

    ~/.bash_login

    Diese Datei hat die gleiche Bedeutung wie ~/.bash_profile. Sie wird verwendet, wenn ~/.bash_profile nicht existiert, ansonsten wird sie danach ausgeführt.

    ~/.bashrc

    Diese Datei ist die lokale benutzerdefinierte Konfigurationsdatei für jede interaktive Shell, die keine Login-Shell ist. Diese Datei kann der User nach seinen Bedürfnissen anpassen.

    ~/.bash_logout

    Diese Datei ist die lokale benutzerdefinierte Logout-Datei. Sie wird bei Beendigung oder Abmeldung aus einer interaktiven Login-Shell ausgeführt und kann zB. für Aufräumarbeiten genutzt werden.

    /etc/inputrc

    Diese Datei ist die systemweite Initialisierungsdatei für die Vorbelegung der Tastatur in der bash zur Konfiguration von readline.

    ~/.inputrc

    Diese Datei enthält die lokale benutzerdefinierte readline-Konfiguration.



letzte Änderung am 19.07.2016