Skip to main content

Command Palette

Search for a command to run...

Useful format specifiers for printf in Bash

Published
1 min read
Useful format specifiers for printf in Bash
M

Hey, I'm a postgraduate in Cyber Security with practical experience in Software Engineering and DevOps Operations. The top player on TryHackMe platform, multilingual speaker (Kazakh, Russian, English, Spanish, and Turkish), curios person, bookworm, geek, sports lover, and just a good guy to speak with!

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

More from this blog

M

Maxat Akbanov's blog

259 posts

Postgraduate in Cyber Security with experience in Software Engineering and DevOps Operations.