Difference between printf and echo in Bash

后端 未结 4 1224
悲哀的现实
悲哀的现实 2021-01-21 08:45
$ printf \'apple\' | wc -m
       5
$ echo \'apple\' | wc -m
       6

Why printf prints 5 and echo prints 6 characters?

4条回答
  •  一个人的身影
    2021-01-21 09:48

    First sentence of entry for echo in the bash man page (emphasis mine):

    Output the args, separated by spaces, followed by a newline.

    First sentence of the man page entry for printf:

    Write the formatted arguments to the standard output under the control of the format.

    printf only prints what appears in the format; it does not append an implied newline.

    There may be other difference between echo "foo" and printf "foo", depending on what exactly foo is. The POSIX specification gives implementations broad discretion in how it implements echo, probably to avoid choosing from among the diverse historical implementations as the standard. Use printf when you rely on the precise output.

提交回复
热议问题