Hacker News new | ask | show | jobs
by ndsipa_pomu 1125 days ago
Not a problem until the random string starts with a dash and you get unexpected results from "echo" interpreting it as an option instead of an argument. Using "printf" bypasses that issue as it's clear what the argument is.

Just tested it and ShellCheck is happy with the printf version:

  printf "%s\n" "$(tr -dc A-Za-z0-9 </dev/urandom | dd count=1 bs=16 2>/dev/null)"
It's also got a stylistic improvement (in my opinion, anyhow) in that the line feed is explicit in the printf command rather than being almost a side effect of echo.

Edit: I see your point about the "tr" not enabling a dash, so my example falls a bit flat, but my point stands in other scenarios. It's good practise to avoid echo where feasible. I think the double quotes will also protect in this instance. The problem with relying on the tr string to not foul up echo is that you may later adapt the code and use a different translate string which could then introduce a tricky bug to track down.