Cybersecurity Updates & Tools

Bash printf Command Explained With Examples

Introduction

The printf command in Bash is used to print formatted text in the terminal. It is similar to the echo command, but printf gives more control over output formatting. With printf, you can control spacing, new lines, numbers, columns, and text alignment.

If you are learning Bash scripting, the printf command is very useful. It helps you create clean output, formatted reports, tables, logs, menus, and system information scripts. For Linux automation and cybersecurity scripts, formatted output makes results easier to read and understand.

What Is The printf Command In Bash?

The printf command prints text using a format string.

Basic syntax:

printf "format" values

Example:

printf "Hello, Bash scripting\n"

Output:

Hello, Bash scripting

The \n adds a new line. Unlike echo, printf does not automatically add a new line unless you include \n.

Basic printf Example

Create a new Bash script:

nano printf-example.sh

Add the following code:

#!/bin/bashprintf "Welcome to Bash scripting\n"printf "This is printed using printf\n"

Save and run it:

chmod +x printf-example.sh./printf-example.sh

Output:

Welcome to Bash scriptingThis is printed using printf

Using Variables With printf

You can use variables inside printf.

#!/bin/bashname="Kali Linux"topic="Bash Scripting"printf "Name: %s\n" "$name"printf "Topic: %s\n" "$topic"

Here, %s is used for strings.

Output:

Name: Kali LinuxTopic: Bash Scripting

Common printf Format Specifiers

FormatMeaning
%sString
%dInteger number
%fFloating-point number
\nNew line
\tTab space

Example:

#!/bin/bashtool="Nmap"ports=1000printf "Tool: %s\n" "$tool"printf "Ports scanned: %d\n" "$ports"

Create A Simple Table Using printf

The printf command is very useful for creating aligned output.

#!/bin/bashprintf "%-15s %-10s\n" "Tool" "Use"printf "%-15s %-10s\n" "Nmap" "Scanning"printf "%-15s %-10s\n" "Curl" "Requests"printf "%-15s %-10s\n" "Grep" "Search"

Output:

Tool            UseNmap            ScanningCurl            RequestsGrep            Search

The %-15s means print a left-aligned string with 15 spaces.

Cybersecurity Example: Format Scan Result

#!/bin/bashhost="192.168.1.1"status="Online"printf "Host: %-15s Status: %s\n" "$host" "$status"

This type of formatting is useful when displaying scan results, log summaries, or system reports.

Conclusion

The Bash printf command is a powerful way to print formatted output. It gives better control than echo and is useful for creating clean terminal output, reports, tables, and logs.

For beginners, learning printf helps improve the quality of Bash scripts. It is especially useful in Linux automation, cybersecurity scripting, system monitoring, and command-line tools where readable output matters