Bash 4.3 Substring Negative Length on OS X

While flabdablet's solution only works for fixed length strings you can use this as a drop-in replacement for dynamically sized strings:

echo ${STR:6:$((${#STR} - 6 - 1))}

In detail:

  • ${#STR} returns the length of the string.
  • $((a - b - c)) does mathematical subtraction
  • ${STR:start:len} returns a substring.

So combined the second argument to the substring expression is the length of the string minus the starting offset minus the value you would specify as negative value in the newer bash syntax.


${STR:6:${#STR}-7} should be a working drop-in replacement for ${STR:6:-1} if STR is guaranteed to contain at least 7 characters. If it could be shorter, this will also cause OS X bash to complain about negative lengths, or go horribly wrong on bash versions that support negative lengths being taken as from-the-right offsets.