Your code is leaving the output of echo
exposed to the shell for interpretation. Don't do that, always quote strings/variabes until if/when you need to remove the quotes. Populate then use a quoted array of the values instead:
ver_to_num() {
local -a ver
IFS=. read -ra ver <<< "$1"
printf '%03d' "${ver[@]}"
}
See https://mywiki.wooledge.org/Quotes and https://mywiki.wooledge.org/BashFAQ/050 for more information.
Unlike the currently accepted answer the above:
- Will work for any number of digits in the version string, not just 4.
- Won't corrupt variables in the calling code that have the same name(s) as variables used inside the function.
003018001001
(GNU bash 5.2.37 / GNU coreutils 9.6)printf "%03d" '3 18 1 1'
, which would happen if you did something like wrapping the"$(echo ... | tr ....)"
in double quotes; is this an exact copy of your code?$(echo ... | tr ...)
) with a simple parameter substitutionprintf "03d ..." ${1//./ }
IFS=
earlier in your script? That would explain the behavior described, as your code depends on word-splitting on IFS to behave as-intended (something both answers work around).