Skip to content

printf

The printf command behaves similarly to the C printf() function and gives you more control over formatting


Print a sequence of numbers

for i in $(seq 0 99); do printf '%s\n' "$i"; done

Print alphabet in order

i=97; while [ $i -le 122 ]; do printf '%b\n' "\\$(printf '%03o' "$i")"; i=$((i+1)); done

Print a horizontal line (minimal ash where tput is not installed)

printf '%*s\n' "${COLUMNS:-80}" '' | tr ' ' "${1-_}" 

Print a horizontal line (bash)

printf -v _hr "%*s" $(tput cols) && echo ${_hr// /${1--}}

Print a horizontal line (ash)

w=${COLUMNS:-80}; i=0; while [ $i -lt "$w" ]; do printf '%s' "${1--}"; i=$((i+1)); done; printf '\n'

Print date with colorized Date

printf "\033[33mDate:\033[37m %s\033[0m\n" "$(date)"

Print a random uuid

printf '%08x-%04x-%04x-%04x-%012x\n' $RANDOM$RANDOM $RANDOM $RANDOM $RANDOM $RANDOM$RANDOM$RANDOM

Print a random uuid in ash shell

hexdump -n16 -e '4/4 "%08x" 1 "\n"' /dev/urandom | sed 's/\(........\)\(....\)\(....\)\(....\)\(............\)/\1-\2-\3-\4-\5/'

Repeat printing string 5 times

printf 'hello world\n%.0s' {1..5}

Display each directory in $PATH on a separate sine

printf ${PATH//:/\\n}

List all files in every directory defined in $PATH

printf "%s\n" ${PATH//:/\/* }

Enumerate all executable files in $PATH with Absolute Paths

(IFS=:; for d in $PATH; do for f in "$d"/*; do [ -f "$f" ] && [ -x "$f" ] && printf '%s\n' "$f"; done done) | sort -u

Enumerate all executable filenames available in $PATH

(IFS=:; for d in $PATH; do for f in "$d"/*; do [ -f "$f" ] && [ -x "$f" ] && printf '%s\n' "${f##*/}"; done; done) | sort -u

Zero-pad integers to 4 digits

printf '%04d\n' 1 23 456

Left and right align text in columns

printf '%-10s %10s\n' "USER" "SHELL"

Print floating point numbers with precision

printf '%.3f\n' 3.1415926535

Print table headers with dynamic width

printf '%-15s %-10s %-5s\n' "Username" "Shell" "UID"

Convert decimal to hexadecimal

printf '0x%X\n' 255

Convert decimal to octal

printf '0%o\n' 755

Print binary representation (bash arithmetic)

printf '%08d\n' "$(echo "obase=2; 13" | bc)"

Escape special characters safely

printf '%q\n' 'hello world & $(rm -rf ~/somefile)'

Command substitution inside double quotes is executed BEFORE printf runs

printf '%s\n' "$(echo injected)"

Print NUL-terminated strings (for xargs -0)

printf '%s\0' file1 file2 file3

Generate a progress bar

p=30; w=50; printf '[%-*s] %d%%\n' "$w" "$(printf '%*s' $((p*w/100)) | tr ' ' '#')" "$p"

Print colored success and error messages

printf '\033[32m[OK]\033[0m Operation completed\n'

Timestamped log entry

printf '[%(%F %T)T] %s\n' -1 "Service started"

Print environment variables in key=value format

printf '%s=%q\n' USER "$USER"

Create formatted CSV output

printf '"%s","%s","%s"\n' "alice" "1000" "/bin/bash"

Emulate Perl String Repetition Mechanism

printf '%*s\n' 20 | tr ' ' '#'

Invert Pattern Matching for Directory Indexing

printf "%s\n" !(pattern) ## ksh, or bash with shopt -s extglob

Generate Fixed-Length Sequence of Hyphens via Octal Padding

printf "%.50d" 0 | tr 0 -

Generate Fixed-Length Sequence of Hyphens via Whitespace Padding

printf "%50s\n"|tr ' ' -

Convert Hexadecimal Notation to Decimal Integer

printf "%d\n" \0x64

Extract Approximate Local German Time via Twitter API Scraping

printf "%02d:%02d\n" $(curl -s "[http://search.twitter.com/search?from=zurvollenstunde&rpp=1](http://search.twitter.com/search?from=zurvollenstunde&rpp=1)" | grep -E '(Es ist jetzt|ago)'  | sed 's/<[^>]*>//g;s/[^[:digit:]]//g'  | xargs )

Enumerate Executables Across System Environment Variables

printf "%s\n" ${PATH//:/\/* }

Compute Message Digest 5 Checksum of Standard Input Stream

printf "$string" | md5sum

Format Environment Substrings into Newline-Separated Output

printf ${PATH//:/\\n}

Encode Simple Authentication and Security Layer Plaintext Credentials

printf '\!:1\0\!:1\0\!:2' | mmencode | tr -d '\n' | sed 's/^/AUTH PLAIN /'

Render Dynamic Terminal-Width Separator Line Using Terminfo Controls

printf -vl "%${COLUMNS:-`tput cols 2>&-||echo 80`}s\n" && echo ${l// /-};

Modify Virtual Console Dimension Constraints via Escape Sequences

printf "\e[8;70;180;t"

Render Dynamic Terminal-Width Separator Line Using Environment Shell Variables

printf -v row "%${COLUMNS}s"; echo ${row// /#}

Construct Matrix Representation of Standard Telephony Interface Layout

printf "%s\t%s\t%s\n" {1..9} '*' 0 '#'

Prepend Absolute Working Directory Pathway to Current Nodes

printf "$PWD/%s\n" *

Apply Thousands Separator Locales to Numeric Formatting Fields

printf "%'d\n" 1234567

Output Pseudorandom Multibyte Unicode Character Encodings

printf "\U$(printf '%x' $((RANDOM%79+128512)) )"

Decode Percent-Encoded Uniform Resource Identifier Strings

printf $(echo -n $1 | sed 's/\\/\\\\/g;s/\(\%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g')

Render Dynamic Terminal-Width Separator Line Using Real-time Terminfo Queries

printf "%`tput cols`s"|tr ' ' '#'

Filter Hidden Files and Directories Within Target Context

printf "%s\n" .*

Project High-Contrast Terminal-Wide Visual Highlight Bar

printf "\e[7m%-`tput cols`s\e[0m\n" "Full width highlighted line"

Serialize Array Indices into Space-Separated Flag Formats

printf  " -e %s" ${ARRAY[*]}

Generate High-Entropy Four-Byte Integers via Kernel Entropy Harvester

printf %d 0x`dd if=/dev/urandom bs=1 count=4 2>/dev/null | od -x | awk 'NR==1 {print $2$3}'`

Translate Character Constants to Decimal ASCII Equivalent Codes

printf "%d\n" "'A" "'B"

Generate Delimited Pseudorandom Passphrases from System Dictionaries

printf '%s-%s-%s-%s\n' $(grep -v "[A-Z]\|'" /usr/share/dict/british | shuf -n 4)

Generate Sequential Hexadecimal Stream Structures

printf "%x\n" $(seq 0 255) | xargs -n1 -IH echo -ne \\xH > test.dat

Aggregate File Type Distribution Counters within Target Subtree

printf "\n%25s%10sTOTAL\n" 'FILE TYPE' ' '; for ext in $(find . -iname \*.* \vert{} egrep -o '\.[^[:space:].]+$' | egrep -v '\.svn*' | sort -f | uniq -i); do count=$(find . -iname \*$ext | wc -l); printf "%25s%10s%d\n" $ext ' '$count; done

Fetch and Calculate Real-Time Cryptocurrency Fee Rates with Timestamps

printf %g "$(bitcoin-cli estimatesmartfee 6 "ECONOMICAL" | jq .feerate*100000)";printf " sat/B estimated feerate for 6 confirmations as of $(date +%c)\nDivide by 100,000 to get btc/KB\n"

Repeat Arbitrary String Sequences Without Intervening Spacing Fields

printf  'xyz%.0s' {1..20}

Serialize Array Indices into Comma-Separated Formats via Output Truncation

printf "%s," "${LIST[@]}" \vert{} cut -d "," -f 1-${#LIST[@]}

Purge Terminal Display and Instantly Flush Scrollback Buffers

printf "\ec"

Invert File Line Sequences Utilizing Line Editor Scripting Subsystems

printf "g/^/m0\nw\nq"|ed $FILE

Construct Unique Identifiers from Cryptographic Hashes and Interface Constants

printf $(( echo "obase=16;$(echo$$$(date +%s%N))"|bc; ip link show|sed -n '/eth/ {N; p}'|grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'|head -c 17 )|tr -d [:space:][:punct:]  |sed 's/[[:xdigit:]]\{2\}/\\x&/g')|sha1sum|head -c 32; echo

Render Dynamic Terminal-Width Breakline Elements Using Equal Signs

printf "%$(tput cols)s\n"|tr ' ' '='

Execute Integer Loops with Fixed Width Padding Formats

printf "%02u " {3..20}; echo