Hacker News new | past | comments | ask | show | jobs | submit login

The thing with echo is repeated again and again but not a problem in the code i've just posted (due to A-Za-z0-9).

And i do require the line feed. Following shellcheck's advice broke the code.




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.


I'd also add that in the cases where you disagree with shellcheck (it doesn't get everything correct all the time), you can include a disabling comment just before the line to tell shellcheck that you know best:

# shellcheck disable=SC2005




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: