bhylu.com

Advertisements

Bash printf and echo

Print text with predictable formatting and keep input out of the format string.

How it works

printf gives explicit control over formatting and newline characters. echo is convenient for simple interactive text, but option and escape handling varies across implementations and shell settings. A fixed printf format separates data from instructions. This matters when a label contains percent signs or a leading dash that another command might interpret as an option.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

printf-echo.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
label="North map: 50% draft"
printf "%s\n" "$label"
echo "Ready"

Expected result

North map: 50% draft
Ready

The percent sign is part of the data supplied to %s, so it is not interpreted as another formatting directive. The simple echo example has no options or escape sequences. Use printf for scripts that need reliable output, particularly when printing values received from parameters or files.

Primary technical reference: Bash documentation.