1

This isn't a question of printf vs echo.

I'm trying to edit my script to use printf exclusively, and I have the following in my code:

echo >&2 'Failed to initialize REPL repo. Please report this!'

If I replace echo with printf, will it introduce any side effects (because of the >&2)?

printf >&2 'Failed to initialize REPL repo. Please report this!\n'

I couldn't find an answer in askubuntu. Either there isn't one or the search is ignoring the > and & characters.

Damian Rivas
  • 206
  • 1
  • 8
  • My question is fine. I do not need convincing of using one over the other, I need to know what happens when I replace `echo` with `printf` in that particular line. – Damian Rivas Dec 21 '18 at 01:49

2 Answers2

4

A redirection like >&2 is a feature of the shell running your script, the program whose output gets redirected is not relevant for it. Yes, if you only ask about the redirection, that’s the same – you don’t have to worry about it unless you change the shell. See your shell‘s manual for details about this feature, e.g. man bash/REDIRECTION for bash.

There’s a nice answer about the differences between echo and printf over on Unix & Linux: Why is printf better than echo?

As for why you can’t search for symbols on AU, see this meta Q&A: How to search AU for a string containing “$”?

dessert
  • 39,392
  • 12
  • 115
  • 163
  • Thank you, the reason for my doubts was all articles including the one you linked show examples like `echo >&2` but not `printf >&2`. Your explanation for `>&2` is perfect. Thanks. – Damian Rivas Dec 19 '18 at 22:36
3

If I replace echo with printf, will it introduce any side effects (because of the >&2)?

The >&2 part has nothing to do with either echo nor printf. The >& is a shell redirection operator, where in this case it duplicates stdout (implied, though could be referenced explicitly with 1>&2) of the command to stderr ( file descriptor 2). They can appear in any order in a command in bourne-like shells. The only issue that can happen is with csh shell and its derivatives(see related post). So, so long as you are using bourne-like shells ( dash, bash, ksh ) you should be fine.

As for printf vs echo generally printf is preferred because it's more portable. See Why is printf better than echo?

Sergiy Kolodyazhnyy
  • 103,293
  • 19
  • 273
  • 492