YouTip LogoYouTip

Linux Shell Printf

In the previous chapter, we learned about the Shell `echo` command. In this chapter, we will learn about another Shell output command, `printf`.\\n\\n`printf` (print formatted) is a Shell command used for formatted output. It originates from the `printf()` function in the C language.\\n\\nUnlike `echo`, `printf` does not automatically append a newline character, and it allows precise control over the output format.\\n\\n`printf` is defined by the POSIX standard, so scripts using `printf` have better portability than those using `echo`.\\n\\n`printf` uses arguments separated by quoted text or spaces. You can use format strings within **printf**, and you can also specify the width, left/right alignment, etc., of the strings. By default, `printf` does not automatically add a newline character like `echo` does; we can manually add `n`.\\n\\n### Why use printf?\\n\\n1. **Format Control**: You can specify field width, precision, and alignment.\\n2. **Type Safety**: Different types of data (integers, floating-point numbers, strings, etc.) have corresponding format specifiers.\\n3. **Portability**: Behavior is more consistent across different systems and Shells.\\n4. **Complex Output**: Suitable for generating structured output like tables and reports.\\n\\n### Basic Syntax\\n\\nSyntax of the printf command:\\n\\nprintf format-string [arguments...]\\n**Parameter Description:**\\n\\n* **format-string**: A string containing ordinary characters and format specifiers.\\n* **arguments...**: Variables or values corresponding to the format specifiers.\\n\\nFormat specifiers start with the `%` character, followed by one or more characters to specify the output format. Commonly used format specifiers include:\\n\\n* `%s`: String\\n* `%d`: Decimal integer\\n* `%f`: Floating-point number\\n* `%c`: Character\\n* `%x`: Hexadecimal number\\n* `%o`: Octal number\\n* `%b`: Binary number\\n* `%e`: Floating-point number in scientific notation\\n\\n### Workflow\\n\\n1. Parse the format string; output ordinary characters directly when encountered.\\n2. When a format specifier (starting with `%`) is encountered:\\n * Read the next argument.\\n * Process the argument according to the format specified by the specifier.\\n * Insert the result into the output.\\n\\n3. After processing all format specifiers, output the final result.\\n\\n* * *\\n\\n## Practical Examples\\n\\n### 1. Basic Usage\\n\\n## Example\\n\\n# Simple String Output\\n\\nprintf"Hello, World!n"\\n\\n# Output with variables\\n\\nname="Alice"\\n\\nprintf"Hello, %sn""$name"\\n\\n**Execution and Output**:\\n\\n## Example\\n\\n$ bash script.sh\\n\\n Hello, World!\\n\\n Hello, Alice\\n\\n### 2. Common Format Specifiers\\n\\n## Example\\n\\n# Integer\\n\\nprintf"Decimal: %dn Hex: %xn Octal: %on"255 255 255\\n\\n# Floating-point number\\n\\nprintf"Float: %fn Scientific: %en"3.14159 3.14159\\n\\n# Strings\\n\\nprintf"Name: %sn""Bob"\\n\\n# Character\\n\\nprintf"First letter: %cn""A"\\n\\n**Execution Result**:\\n\\nDecimal: 255Hex: ff Octal: 377Float: 3.141590Scientific: 3.141590e+00Name: BobFirst letter: A\\n### 3. Format Control\\n\\n## Example\\n\\n# Field width and alignment\\n\\nprintf"|%10s|n|%-10s|n""right""left"\\n\\n# Leading zeros for numbers\\n\\nprintf"Year: %04dn"23\\n\\n# Floating-point numberPrecision\\n\\nprintf"Pi: %.2fn"3.14159\\n\\n**Execution Result**:\\n\\n| right||left |Year: 0023Pi: 3.14\\n### 4. Multiple Argument Processing\\n\\n## Example\\n\\nprintf"%-10s %5d %8.2fn""Apple"5 2.5"Orange"3 1.75\\n\\n**Execution Result**:\\n\\nApple 5 2.50Orange 3 1.75\\n\\n* * *\\n\\n## Extended Applications\\n\\n### 1. Creating Table Output\\n\\n## Example\\n\\n#!/bin/bash\\n\\n# Table header\\n\\nprintf"%-15s %10s %10s %10sn""Item""Quantity""Price""Total"\\n\\n# Separator line\\n\\nprintf"%-15s %10s %10s %10sn""---------------""----------""----------""----------"\\n\\n# Data row\\n\\nprintf"%-15s %10d %10.2f %10.2fn""Notebook"3 2.50 7.50\\n\\nprintf"%-15s %10d %10.2f %10.2fn""Pen"5 1.20 6.00\\n\\nprintf"%-15s %10d %10.2f %10.2fn""Eraser"2 0.50 1.00\\n\\n# Total row\\n\\nprintf"%-15s %10s %10s %10.2fn""""""Total:"14.50\\n\\n**Output Effect**:\\n\\nItem Quantity Price Total--------------- ---------- ---------- ----------Notebook 3 2.50 7.50Pen 5 1.20 6.00Eraser 2 0.50 1.00 Total: 14.50\\n### 2. Progress Bar Implementation\\n\\n## Example\\n\\n#!/bin/bash\\n\\nfor i in{1..20}; do\\n\\nprintf"r Progress: [%-20s] %d%%" $(printf"%${i}s"|tr' ''#') $((i*5))\\n\\nsleep 0.1\\n\\ndone\\n\\nprintf"n"\\n\\n**Execution Effect**: Displays a gradually increasing progress bar.\\n\\n### 3. Color Output\\n\\n## Example\\n\\n#!/bin/bash\\n\\nRED='33[0;31m'\\n\\nGREEN='33[0;32m'\\n\\nNC='33[0m'# No Color\\n\\nprintf"${RED}Error:${NC} Something went wrongn"\\n\\nprintf"${GREEN}Success:${NC} Operation completedn"\\n\\n### 4. Format Output\\n\\nNext, I will use a script to demonstrate the powerful features of `printf`:\\n\\n## Example\\n\\n#!/bin/bash\\n\\n# author:\\n\\n# url:example.com\\n\\nprintf"%-10s %-8s %-4sn" Name Gender Weightkg \\n\\nprintf"%-10s %-8s %-4.2fn" Guo Jing Male 66.1234\\n\\nprintf"%-10s %-8s %-4.2fn" Yang Guo Male 48.6543\\n\\nprintf"%-10s %-8s %-4.2fn" Guo Fu Female 47.9876\\n\\nExecute the script, and the output is as follows:\\n\\nName Gender Weightkg Guo Jing Male 66.12Yang Guo Male 48.65Guo Fu Female 47.99\\n%s %c %d %f are all format substitution specifiers. **%s** outputs a string, **%d** outputs an integer, **%c** outputs a character, and **%f** outputs a real number in decimal form.\\n\\n%-10s refers to a width of 10 characters (**-** indicates left alignment; without it, it means right alignment). Any character will be displayed within a 10-character-wide field. If it's not enough, it will be automatically padded with spaces; if it exceeds, the entire content will still be displayed.\\n\\n%-4.2f means formatting as a decimal, where **.2** means keeping 2 decimal places.\\n\\n## Example\\n\\n#!/bin/bash\\n\\n# author:\\n\\n# url:example.com\\n\\n# format-stringFor double quotes\\n\\nprintf"%d %sn"1"abc"\\n\\n# Single quotes and double quotes have the same effect \\n\\nprintf'%d %sn'1"abc"\\n\\n# Output without quotes is possible\\n\\nprintf%s abcdef\\n\\n# The format specifies only one parameter, but extra parameters are still output according to the format, format-string Reused\\n\\nprintf%s abc def\\n\\nprintf"%sn" abc def\\n\\nprintf"%s %s %sn" a b c d e f g h i j\\n\\n# If there are no arguments, then %s Replace with NULL,%d Use 0 instead\\n\\nprintf"%s and %d n"\\n\\nExecute the script, and the output is as follows:\\n\\n1 abc 1 abc abcdefabcdefabc def a b c d e f g h i j and 0\\n\\n* * *\\n\\n## printf Escape Sequences\\n\\n| Sequence | Description |\\n| --- | --- |\\n| a | Alert character, usually the ASCII BEL character |\\n| b | Backspace |\\n| c | Suppress (do not display) any trailing newline characters in the output result (only valid in argument strings controlled by the %b format specifier). Furthermore, any characters remaining in the argument, any subsequent arguments, and any characters remaining in the format string are ignored |\\n| f | Formfeed |\\n| n | Newline |\\n| r | Carriage return |\\n| t | Horizontal tab |\\n| v | Vertical tab |\\n| \\\\ | A literal backslash character |\\n| ddd | Represents a character with a 1 to 3 digit octal value. Only valid in format strings |\\n| ddd | Represents a 1 to 3 digit octal value character |\\n\\n## Example\\n\\n$ printf"a string, no processing:n""An B"\\n\\n a string, no processing:\\n\\n$ printf"a string, no processing:
← Docker Compose Ls CommandDocker Compose Ps Command β†’