Consider a this string containing an integer
nanoseconds=$(date +%s%N)
when I want to strip off the last six characters, what would be semantically better?
Stripping just the characters off the string
nanoseconds=$(date +%s%N)
milliseconds=${nanoseconds%??????}
or dividing the value by 1000000
milliseconds=$((nanoseconds / 1000000))
EDIT
Sry for not being clear. It’s basically for doing a conversion from nanoseconds to milliseconds. I think I answered my own question…
Both are equivalent, but in general I would consider the former method to be safer. The first method is explicit and does precisely what you want to do: to remove a substring from the back of the string.
The other one is a mathematical operation that relies on correct rounding. Although I cannot imagine where it would fail, I would prefer the first method.
Unless, of course, what you really want is not stripping the last three characters but dividing by 1000 🙂
Post scriptum: hah, of course I know where it would fail. Let value=”123″.
${value%???}strips the last three digits, as intended, leaving an empty string.$(( value / 1000 ))results in value equal to"0"(a string of length of 1).EDIT: since we know now that it is not about stripping characters, but rounding, clearly dividing by 1000 is the correct way of approaching the problem 🙂