I tried switching from echo to printf in my bash scripts, following some advice I found online. I used a sed command to replace echo statements with printf, but now I'm facing strange issues where many strings are getting truncated. When I switched back to echo, everything worked fine again. I'm curious if printf struggles with UTF-8 characters or if there's another reason this is happening. I also tried using %b instead of %s, but that didn't help. Can anyone shed some light on this?
3 Answers
Be careful with blindly replacing echo with printf. For example, I had a line that caused issues because of how I handled IFS and echo. It’s often better to keep echo where it works unless you're rewriting the whole script with printf.
Also, I think that line isn't functioning as you expect. If you want to fill an array with grep's output, use mapfile instead of read!
It's actually better to use printf for new code rather than just bulk-replacing echo in existing scripts. If echo works, it's often not worth the hassle of swapping it out.
When using printf, remember that multiple arguments are printed on separate lines, unlike echo which prints them all on one line, separated by spaces. This might explain some of the truncation you're seeing if your strings contain newline characters.
Interesting point! I thought spaces were the main issue, but I found that accented characters seemed to cause the truncation instead.
Totally agree! Using echo in a subshell can complicate things. It’s cleaner to set IFS directly like this: IFS=$'nb'.