Where to start First steps track · 15 stages
Linux Labs

printf and echo — printing text in scripts

cheat sheet · bash / coreutils https://lab.dimsanych.ru/en/wiki/printf/

Cheat sheet

  • printf '%s\n' "$var" a reliable way to print a string
  • printf '%-10s %5d\n' name 42 alignment
  • printf '%.2f\n' 3.14159 two digits after the point
  • printf '%05d\n' 42 leading zeros
  • printf -v v '%s' "$x" into a variable
  • printf '%(%F)T\n' -1 a date, without calling date
  • printf '%q\n' "$s" escape for the shell

Options

printf barely has any options of its own — control happens through the format string; the exception is -v, which writes the result into a variable instead of printing it. echo's options, by contrast, define its whole behavior: -n drops the trailing newline, -e/-E turn interpretation of \n/\t in the argument on and off — the default behavior of -e differs between bash's echo and /bin/echo, which is why printf is more reliable in scripts.

Loading…