转换为数字

基本类型 / 字符串

#to integer: arithmetic reads the string itself
strNumber="42"
number=$((strNumber))
#number is 42

#"42abc" is an error inside $(( )), so check the text first
strMixed="42abc"
if [[ "$strMixed" =~ ^-?[0-9]+$ ]]; then
    checked=$((strMixed))
else
    checked=0
fi
#checked is 0

#a leading zero means octal: 10# forces base 10
strZero="08"
fromZero=$((10#$strZero))
#fromZero is 8

#bash has no fractional numbers: the text "3.14" stays a string,
#bc and awk do the arithmetic with it
strPi="3.14"
doubledPi=$(bc <<< "$strPi * 2")
#doubledPi is 6.28

#replacement of the non-standard delimiter
strHalf="0,5"
half=${strHalf/,/.}
#half is "0.5"
halfPlusOne=$(awk -v h="$half" 'BEGIN { print h + 1 }')
#halfPlusOne is 1.5

echo "number is $number"
echo "checked is $checked"
echo "fromZero is $fromZero"
echo "doubledPi is $doubledPi"
echo "halfPlusOne is $halfPlusOne"