2

I found weird the following bash behaviour in the last command line. For me, it is totally unexpected.

$ set | grep ^BASH_VERSINFO             # Show the array
BASH_VERSINFO=([0]="3" [1]="2" [2]="25" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")

$ echo "${BASH_VERSINFO[@]}"             # Print all array
3 2 25 1 release x86_64-redhat-linux-gnu

$ echo "${BASH_VERSINFO[@]%e}"           # Print all array removing final 'e' of every member
3 2 25 1 releas x86_64-redhat-linux-gnu

$ i=4; echo "${BASH_VERSINFO[i]}"        # Print an array member
release
$ i=4; echo "${BASH_VERSINFO[i++]}"      # Print an array member and increase the 'i' variable
release
$ i=4; echo "${BASH_VERSINFO[i]%e}"      # Print an array member removing the final 'e'
releas
$ i=4; echo "${BASH_VERSINFO[i++]%e}"    # Why does bash use the next member?
x86_64-redhat-linux-gnu

It seems that bash preincrements the 'i' variable.

Similar weird behaviour:

$ i=5; echo "${BASH_VERSINFO[--i]}"    # Print array member ${BASH_VERSINFO[4]}. 'i' is descreased one time.
release
$ i=5; echo "${BASH_VERSINFO[--i]%e}"  # Print array member ${BASH_VERSINFO[3]%e}. 'i' is descreased two times.
1

Does anyone can tell me that behaviour?

Thanx in advance

1 Answer 1

5

This seems to be a bug that has been fixed, possibly this one:

(from the bash ChangeLog -- changes between bash-4.2-alpha and bash-4.1-release)

Fixed a bug in arithmetic expansion that caused the index in an array expansion to be evaluated twice under certain circumstances.

Worksforme:

$ echo "${BASH_VERSINFO[*]}"
4 2 42 1 release i586-pc-linux-gnu
$ i=4; echo "${BASH_VERSINFO[i++]}"; echo "$i"
release
5
$ i=4; echo "${BASH_VERSINFO[i++]%e}"; echo "$i"
releas
5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.