4

I came across string length manipulation in bash 4.1.2 for two strings

First: 1000000000000000000

developer@kernel ~> echo ${#1000000000000000000}
0
developer@kernel ~> s1=1000000000000000000
developer@kernel ~> echo ${#s1}
19

Second: 10000000000000000000

developer@kernel ~> echo ${#10000000000000000000}
19
developer@kernel ~> s2=10000000000000000000
developer@kernel ~> echo ${#s2}
20

How to explain the strange those behaviors?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
http8086
  • 1,306
  • 16
  • 37

1 Answers1

8

${#var} is normally the length in characters of ${var}. So ${#1000000000000000000} is the length of the 1000000000000000000th argument to the script. Since your script wasn't called with that many arguments, this is zero.

Apparently there's a limit on the number of positional parameters, and when you try to refer to a parameter beyond that, the results are unpredictable, and varies from system to system. The dividing line appears to be ${#9223372036854775808}, which is 264.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • but the length of 10000000000000000000 is 20, why ${#10000000000000000000} goes to 19? – http8086 Dec 26 '14 at 02:14
  • @hylepo I get 20 for `echo ${#10000000000000000000}`. – Barmar Dec 26 '14 at 02:17
  • @BallPython What does `echo ${0}` return? How long is it? – Barmar Dec 26 '14 at 02:17
  • @Barmar, have you noticed what is the version number of your bash? – http8086 Dec 26 '14 at 02:19
  • I tried this on OS X running bash 3.2.48. I'll try it now on Linux running 4.1.5 and see what I get – Barmar Dec 26 '14 at 02:20
  • Weird, it returns 25. – Barmar Dec 26 '14 at 02:21
  • I think this answer already hits the point of the question. It make no much sense to argument about why ${#xxxxxxxxxxxxx} returns what value, since no one wants to access that positional parameter, and it's beyond the limit anyway. Only the maintainer/developer of bash should be worried about it for security reason. – Robin Hsu Dec 26 '14 at 05:45
  • @Barmar, $0 is "-bash" if you are in bash prompt, which has the length of 5. – http8086 Dec 26 '14 at 08:51
  • 1
    `${#9223372036854775807}` is 0. `${#9223372036854775808}` is 18. The upper bound is 2**63-1 (at least on my system). – Keith Thompson Dec 26 '14 at 19:53
  • @KeithThompson The length of the string format of 9223372036854775808 is 19, so why ${#9223372036854775808} shows 18? – http8086 Dec 27 '14 at 08:13
  • I think we've already established that this behavior is unpredictable. On my Linux system it shows 25. – Barmar Dec 27 '14 at 08:17
  • @Barmar so would you like to improve your answer and then we can close the discussion, since "it just returns the length of the name" is not exactly – http8086 Dec 28 '14 at 09:00