printf — Print formatted text using C-style format specifiers like %s and %d across all 5 shells
Equivalents in every shell
printf "%s\n" "hello"Bash builtin (with the same name as `/usr/bin/printf`). Supports `%s`, `%d`, `%x`, `%f`, `%b` (interpret backslash escapes), and printf-style argument re-use.
printf "%s\n" helloFish calls the external `printf` binary (`/usr/bin/printf` on Linux/macOS, `printf.exe` from Git Bash on Windows). Same format-string semantics; no builtin.
"{0}`n" -f "hello"No `printf` cmdlet. Use the `-f` format operator (`{0}`, `{1}` placeholders) or `[string]::Format()`. `Write-Host -NoNewline` combined with `-f` is the closest in-place printf substitute.
echo helloNo printf. `echo` always appends a newline; for formatting use PowerShell, Git Bash, or WSL.
Worked examples
Print a labeled value with no trailing newline
printf "name: %s" "ada"Write-Host ("name: {0}" -f "ada") -NoNewlineZero-pad a number to four digits
printf "%04d\n" 42printf "%04d\n" 42"{0:0000}" -f 42Print each array element on its own line
printf "%s\n" "${arr[@]}"printf "%s\n" $arr$arr | ForEach-Object { $_ }Gotchas
- Bash builtin `printf` and `/usr/bin/printf` differ subtly — the builtin understands `%q` (shell-quote), the external usually does not. `command printf` forces the external binary.
- `printf "$user_input"` is a *format-string injection vulnerability* — `%s` in user input pulls from the argument list. Always pass user data as an argument: `printf "%s" "$user_input"`.
- PowerShell's `-f` operator uses .NET `string.Format` syntax (`{0:N2}`), NOT C printf (`%.2f`). They cover similar ground but flags, padding, and locale handling all differ — port carefully.
- Fish's `printf` is external, so it shells out for every call — measurably slower than bash's builtin in tight loops. For per-element formatting in fish, prefer `string` builtins where possible.
- Cmd has no printf. The usual hack `echo X` is line-buffered and trims trailing whitespace; for any non-trivial formatting drop to PowerShell with `cmd /c powershell -c "..."`, or call a Git Bash / WSL printf.
WSL & PowerShell Core notes
Common tasks using printf
- Escape a string for safe shell use
Quote / escape a string so it survives word-splitting, glob expansion, and interpretation as multiple arguments — the fix for "spaces in filename break my script" and shell-injection bugs.
- Get the current timestamp
Print the current date / time as either a Unix epoch (seconds since 1970-01-01 UTC) or an ISO 8601 string — for log lines, filenames, expiry calculations, and HTTP `Date` headers.