Open In App

printf command in Linux with Examples

Last Updated : 18 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

printf” command in Linux is used to display the given string, number or any other format specifier on the terminal window. It works the same way as “printf” works in programming languages like C.

Syntax:

$printf [-v var] format [arguments]

Note: printf can have format specifiers, escape sequences or ordinary characters.

Format Specifiers: The most commonly used printf specifiers are %s, %b, %d, %x and %f.

Examples:

  • %s specifier: It is basically a string specifier for string output.
    $printf "%s\n" "Hello, World!"
    

    Output:

  • %b specifier: It is same as string specifier but it allows us to interpret escape sequences with an argument.
    Input:  printf "%s\n" "Hello, World! \n" "From Geeks For Geeks\n"
    
    Output: Hello, World! \n
            From Geeks For Geeks\n
    

    Note: The escape sequence “\n” in the above lines has no special meaning when used with “%s” specifier and is treated just like other characters. If we replace “%s” with “%b“, Then it will be interpreted as a newline character.

    Input :  printf "%b\n" "Hello, World! \n" "From Geeks For Geeks\n"
    Output:  Hello, World! 
    
             From Geeks For Geeks 
    
    

    Example:

    $printf "%b\n" "Geeks" "for" "\nGeeks\n"
    

    Output:

  • %d specifier: It is an integer specifier for showing the integral values.
    $printf "%d\n" "213" "109"
    

    Output:

  • %f specifier: It is used for output of floating point values.
    $printf "%f\n" "1.32" "3.14"
    

    Output:

  • %x specifier: It is used for output of lowercase hexadecimal values for integers and for padding the output.
    $printf "%08x\n" "1024"
    

    Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads