/ /宣言された整数をBashスクリプトの文字列に変更すると、なぜ0になるのか - bash

宣言された整数をBashスクリプトの文字列に変更すると整数が0になる理由 - bash

コード:

#!/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.

私は理由を理解できません number 文字列を割り当てると変更されました "three"number。おもう number 同じままにする必要があります。それは本当に私を驚かせた。

回答:

回答№1は2

から declare のセクション man bash

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

から ARITHMETIC EVALUATION のセクション 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.

一緒に、これらは、あなたが見ている行動が予想される行動であることを明確に述べています。 t h r e e 算術的に評価され、結果として得られる null 値は次のように評価されます 0これを変数に代入します number.

bashのすべての代入は、最初に文字列として解釈されます。 number=10 その 1 0 まず文字列として、それを有効な整数として認識し、そのままの状態にします。 number=three 構文的にも意味的にも有効です number=10これは、あなたのスクリプトが評価された 0number.