A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 9 Ω
Das Banner der Rhetos-Website: zwei griechische Denker betrachten ein physikalisches Universum um sie herum.

Bash printf

Progrmamieren

© 2024 - 2025




Basiswissen


Der Befehl printf unter Bash dient speziell der Verwendung zur Ausgaben von Daten mit Hilfe von unsichtbaren Steuerzeichen. Man kann damit kontrolliert Zeilenumbrüche, Tabulatoren und derlei mehr platzieren.

Formatierung von Textblöcken


printf "ErdgeschichtenArchaikum"

Dieser Befehl schreibt erst das Wort Erdgeschichte auf den Bildschirm. Das Wort Archaikum wird dann am Anfang einer neuen Zeile darunter geschrieben. Die Zeichenfolge n wird dabei nicht ausgeschrieben sondern von dem Befehl printf als ein sogenanntes Steuerzeichen gedeutet. Die möglichen Steuerzeichen sind:

  • " double quote
  • \ backslash
  • a alert (BEL)
  • b backspace
  • c produce no further output
  • e escape
  • f form feed
  • n new line
  • r carriage return
  • t horizontal tab
  • v vertical tab

Formatierung der Inhalte von Variablen


x=4.001
printf "%i" "$x"

Hier wird der Variablen x zuerst der textliche Inhalt 4.001 zugeordnet. Der printf Befehle sagt dann zuerst, dass etwas als Ganzzzahl (i=Integer=Ganzzahl) (%i) ausgegeben werden soll. Anschließend wird gesagt, wo der Befehl die Sache findet, die als Ganzzahl ausgegeben werden soll, nämlich der Inhalt der Variablen x. Auf dem Bildschirm wird entsprechend nur die 4 angezeigt. Die Nachkommastellen werden ohne vorherige Rundung einfach abgeschnitten.Die möglichen Formatierungen von Inhalten von Variablen sind:

  • %b - Print the argument while expanding backslash escape sequences.
  • %q - Print the argument shell-quoted, reusable as input.
  • %d, %i - Print the argument as a signed decimal integer.
  • %u - Print the argument as an unsigned decimal integer.
  • %o - Print the argument as an unsigned octal integer.
  • %x, %X - Print the argument as an unsigned hexadecimal integer. %x prints lower-case letters and %X prints upper-case.
  • %e, %E - Print the argument as a floating-point number in exponential notation. %e prints lower-case letters and %E prints upper-case.
  • %a, %A - Print the argument as a floating-point number in hexadecimal fractional notation. %a prints lower-case letters and %A prints upper-case.
  • %g, %G - Print the argument as a floating-point number in normal or exponential notation, whichever is more appropriate for the given value and precision. %g prints lower-case letters and %G prints upper-case.
  • %c - Print the argument as a single character.
  • %f - Print the argument as a floating-point number.
  • %s - Print the argument as a string.
  • %% - Print a literal % symbol.