0

I am on a bash and I am trying two commands with printf, but getting different results

[bhavukg@XYZ unixTutorial]$ printf "Result is %.3f\n", 8/3

Output:
bash: printf: 8/3: invalid number
Result is 0.000
[bhavukg@XYZ unixTutorial]$ awk 'BEGIN {printf "result is %.3f", 8/3}'

Output:
result is 2.667

My questions is why first printf not able to evaluate the expression. What other changes exist in both printf statements

  • To the shell, 8/3 is just a string. You can perform integer arithmetic using arithmetic expressions using `$((...))` but there is still no floating point (non-integer arithmetic); indeed, using an external tool like Awk or `bc` is the usual workaround. – tripleee Dec 27 '22 at 11:08
  • Asking how `printf` in the shell is distinct from the command with the same name in Awk is rather disingenuous; these are two distinct languages with distinct feature sets and idioms. Both happen to expose `printf` from the underlying C library but that's basically a coincidence. There is no Awk function which corresponds to the shell's `export` command, for example, and no (standard) shell replacement for Awk's `gensub` – tripleee Dec 27 '22 at 11:11
  • A slash is not a valid character inside a number, and that's why printf complains. You need to evaluate the expression. Since you want to have floating point arithmetic here, you either have to use a shell which supports floats natively (zsh) or use another scripting language which does (bc, awk, ruby, ...), as tripleee suggested. – user1934428 Dec 27 '22 at 12:06

0 Answers0