Useful format specifiers for printf in Bash

Photo by Lukas on Unsplash

Useful format specifiers for printf in Bash

The bash printf command is a tool used for creating formatted output. Here are some examples of some of the most useful printf format specifiers:

  1. %s - used to print a string. For example:

    name="John"
    printf "Hello, %s!\n" $name
    

    Output: Hello, John!

  2. %d - used to print an integer. For example:

    x=5
    printf "%d\n" $x
    

    Output: 5

  3. %f - used to print a floating-point number. For example:

    x=3.14159
    printf "%.2f\n" $x
    

    Output: 3.14

  4. %x - used to print an integer in hexadecimal format. For example:

    x=255
    printf "%x\n" $x
    

    Output: ff

  5. %o - used to print an integer in octal format. For example:

    x=255
    printf "%o\n" $x
    

    Output: 377

  6. %c - used to print a single character. For example:

    x='A'
    printf "%c\n" $x
    

    Output: A

  7. %b - used to print an integer in binary format. For example:

    x=5
    printf "%b\n" $x
    

    Output: 101

  8. %e - used to print a floating-point number in scientific notation. For example:

    x=3.14159
    printf "%e\n" $x
    

    Output: 3.141590e+00

Reference:

  1. printf man page
  2. Bash printf - How to Print a Variable in Bash