Hacker News new | ask | show | jobs
by zelphirkalt 640 days ago
Why would you change a shell (sh?) script into a Bash script? And why would you change [[ into [ expressions, which are not Posix, as far as I remember? And why make the distinction for numeric variablesand not simply make the usage the same, consistent for everything? Does it also leave away the double quotes there? That even sounds dangerous, since numeric variables can contain filenames with spaces.

Somehow whenever people dance to the Google code conventions tune, I find they adhere to questionable practices. I think people need to realize, that big tech conventions are simply their common debominator, and not especially great rules, that everyone should adopt for themselves.

1 comments

>That even sounds dangerous, since numeric variables can contain filenames with spaces.

Or filenames that contain the number zero :D

    #!/bin/sh
    #
    # Usage : popc_unchecked BINARY_STRING
    #
    #   Count number of 1s in BINARY_STRING.  Made to demonstrate a use of IFS that
    #   can bite you if you do not quote all the variables you don't want to split.
    
    len="${#1}"
    count() { printf '%s\n' "$((len + 1 - $#))"; }
    saved="${IFS}"
    IFS=0
    count 1${1}1
    IFS="${saved}"
    
    # PS: we do not run the code in a subshell because popcount needs to be highly
    # performant (≖ ᴗ ≖ )