1

Code:

#!/bin/bash

declare -i number
# The script will treat subsequent occurrences of "number" as an integer.       

number=3
echo "Number = $number"     # Number = 3

number=three
echo "Number = $number"     # Number = 0
# Tries to evaluate the string "three" as an integer.

I cannot figure out why number changed when I assign a string "three" to number. I think number should stay the same. That really surprised me.

5
  • 3
    This is just not supported. The assignment operator does not translate english words into their numerical meaning. If it isn't a number (in digits) then 0 will result. What are you trying to do, in a wider perspective? Commented Dec 1, 2015 at 8:24
  • 3
    Why would it stay the same, you just assigned it a new value... Commented Dec 1, 2015 at 8:26
  • But assign string to a declared integer is illegal, so I think number should stay same just like it failed. Set number to 0 destroy my original data. It is just a example from a bash script book. Commented Dec 1, 2015 at 8:34
  • 2
    no assigning a string is not illegal, it is "interpreted" as a number. e.g. "5+5" is interpreted as 10. You string is interpreted as 0 as a last resort. Commented Dec 1, 2015 at 8:36
  • @geert3 Not quite a last resort; strings are (recursively) evaluated as parameter expansions in an arithmetic context; undefined parameters default to 0. Commented Dec 1, 2015 at 13:22

1 Answer 1

2

From the declare section of man bash:

-i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION) is performed when the variable is assigned a value.

From the ARITHMETIC EVALUATION section of man bash:

The value of a variable is evaluated as an arithmetic expression when...a variable which has been given the integer attribute using declare -i is assigned a value. A null value evaluates to 0.

Together, these clearly state that the behavior you're seeing is the expected behavior. When the characters t h r e e are evaluated arithmetically, the resulting null value is evaluated as 0, which is then assigned to the variable number.

All assignments in bash are interpreted first as strings. number=10 interprets the 1 0 as a string first, recognizes it as a valid integer, and leaves it as-is. number=three is just as syntactically and semantically valid as number=10, which is why your script continues without any error after assigning the evaluated value of 0 to number.

Sign up to request clarification or add additional context in comments.

2 Comments

then casts it to an integer, it doesn't, it's always a string.
@123 Adjusted to recognizes it as a valid integer.

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.