1

I have a simple program to print the command line arguments in zsh. However, I see different behaviour with printf vs echo. Can anyone explain?

#!/bin/zsh
echo "$# @ : "$@"   "
printf "\n"
printf "$# *  $*   "
printf "\n"
printf "$# @ : "$@" \n"

Output:

batman$ ./args  a b c d
4 @ : a b c d   

4 *  a b c d   
4 @ : abatman$ //also gobbles up the newline!!
batman$ 
1
  • Many differences. For instance, printf interprets the first parameter as a format specifier. You can see the effect when you do a ./args '%s %s x y` with your example script. Commented May 11, 2021 at 6:57

1 Answer 1

1

echo and printf (and print) are different commands with different syntaxes and behaviors. Read the documentation for more info:

In Zsh, you should generally prefer print or printf over echo. print provides many more options to control how the input is parsed and where the output is sent, whereas printf gives much more control on the output is formatted. echo is mostly just there for compatibility with other shells.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand the advantages (and disadvantages) of 'printf', but why should we prefer 'print' over 'echo'?
@KimSilverman I added a bit of explanation to my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.