bashprintf

Why does printf fail with "invalid number" within bash script but not at command line?


I have this function in a bash script:

ver_to_num() { 
  printf "%03d%03d%03d%03d" $(echo "$1" | tr '.' ' ')
}

ver_to_num 3.18.1.1 works from the command line. But when used in a script I get:

printf: 3 18 1 1: invalid number

Any idea why I would get this error in this context?


Solution

  • try this:

    This eliminates issues caused by strange whitespace or unexpected extra fields.

    ver_to_num() {
      IFS='.' read -r a b c d <<< "$1"
      printf "%03d%03d%03d%03d" "$a" "$b" "$c" "$d"
    }