11

I have a simple shell function call and I'm using echo and printf commands to print the parameter I'm passing. I have noticed the following:

  1. echo is printing the output
  2. printf is not printing the output

Am I missing something here?

check_host(){
    # prints output
    echo $1

    # does not print the output
    printf $1

    }
check_host $(hostname)
terdon
  • 242,166
S.D.
  • 213

1 Answers1

14

The function you show would print the first argument twice, once with a newline appended, and with no newline at the end of the of second output.

E.g. in an interactive Bash shell, you'd get something like this

user@foo /tmp$ check_host foo
foo
foouser@foo /tmp$ 

The output from printf is there, just not on a line of its own.

The difference between echo and printf is that echo prints a newline at the end even if you don't ask for it (you can prevent that in Bash by using echo -n), and printf works more like the printf() function in C, in that it only prints what you ask. You'll have to explicitly use \n in the printf format string to get the newline.

Note that in general, you'd want to quote those variables and the command substitution to prevent issues with word splitting. This probably isn't a problem with the hostname, but if you have values with whitespace, you'll need it.

So:

check_host() {
    echo "$1"
    printf "%s\n" "$1"
}
check_host "$(hostname)"

Printing arbitrary data with printf should also be done through the %s format specifier as above. Otherwise any % signs in the data would be interpreted by printf.

Also see: Why is printf better than echo?

ilkkachu
  • 138,973