BASH版本相关问题

时间:2012-03-22 21:29:08

标签: bash unix

此陈述在BASH v.4.1.7(1)中有效,但在BASH v.4.2.20(1)

中没有
num=${number:$counter:1}

我得到了“错误的替代”作为错误。有关为何发生这种情况的任何见解? 目标是执行与${string:position:length}类似的操作来获取子字符串。

任何帮助将不胜感激。感谢。

下面添加了包含此行的原始代码(第15行)

#!/bin/bash

echo "Please enter a number: "
read number

counter=0
answer=0
end=$(( ${#number} - 1 ))

echo -n "The sum of all digits of "
echo -n $number
echo -n " is "

while [ $counter -lt ${#number} ] ; do
num=${number:$counter:1}
if [ $counter -lt $end ] ; then
echo -n $num
echo -n "+"
else
echo -n $num
echo -n "="
fi
answer=$(( $answer + $num ))
counter=`expr $counter + 1`
done

echo $answer

1 个答案:

答案 0 :(得分:2)

当我测试时,4.2.20的表达式很好。也许你的环境中有什么东西?

[localhost ~]$ bash --version
GNU bash, version 4.2.20(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[localhost ~]$ number=123
[localhost ~]$ counter=0
[localhost ~]$ echo $number
123
[localhost ~]$ num=${number:$counter:1}
[localhost ~]$ echo $num
1