The printf
command in Bash is a powerful tool for formatting and displaying text. It offers more control over output formatting compared to the simpler echo command.
The basic syntax of the printf command is:
printf format [arguments...]
Where format
is a string containing text and format specifiers, and arguments
are the values to be formatted.
%s
: String%d
: Integer%f
: Floating-point number%x
: Hexadecimal%%
: Literal percent signprintf "Hello, %s!\n" "World"
# Output: Hello, World!
printf "Name: %s, Age: %d, Height: %.2f\n" "Alice" 30 5.75
# Output: Name: Alice, Age: 30, Height: 5.75
The printf command supports various formatting options:
%10s
(right-aligned), %-10s
(left-aligned)%.2f
(two decimal places)%05d
(pad with zeros to 5 digits)printf allows for precise control over field width and alignment:
printf '%-10s | %10s | %5s\n' 'Name' 'Occupation' 'Age'
printf '%-10s | %10s | %5d\n' 'Alice' 'Engineer' 28
printf '%-10s | %10s | %5d\n' 'Bob' 'Designer' 35
# Output:
# Name | Occupation | Age
# Alice | Engineer | 28
# Bob | Designer | 35
The printf command is an essential tool for Bash scripting, offering precise control over output formatting. Its versatility makes it invaluable for creating well-formatted reports, tables, and user interfaces in shell scripts.
For more advanced text manipulation, consider exploring the sed command or the awk command.