将 1 添加到变量无法按预期工作(Bash 算术)

将 1 添加到变量无法按预期工作(Bash 算术)

如果我在 bash 终端中写入以下内容:

A="0012"
B=$((A+1))
echo $B

我得到了 11,而不是我预期的 13!!!!

我在 Google 上搜索过,但根本无法解释,也无法弄清楚如何让数字增加。(我实际上希望以 B="0013" 结尾,并且每次都增加一,因为我将其用作备份的前缀)

答案1

这是因为 以 开头的数字0被 视为八进制bash,因此它执行八进制(基数为 8)加法。要获取此结构的十进制加法,您需要明确定义基数或00根本不使用。

对于十进制,基数为 10,表示为10#

$ A="10#0012"
$ echo $((A+1))
13

答案2

你可以尝试这个命令来得到答案:

A="0012"
echo $A + 1 | bc

有关命令的更多信息bc可以找到这里

bc手册页:

NAME
       bc - An arbitrary precision calculator language

SYNTAX
       bc [ -hlwsqv ] [long-options] [  file ... ]

DESCRIPTION
       bc is a language that supports arbitrary precision numbers with interactive execution of statements.  There are some similarities
       in the syntax to the C programming language.  A standard math library is available by command line  option.   If  requested,  the
       math  library is defined before processing any files.  bc starts by processing code from all the files listed on the command line
       in the order listed.  After all files have been processed, bc reads from the standard input.  All code is executed as it is read.
       (If a file contains a command to halt the processor, bc will never read from the standard input.)

       This  version of bc contains several extensions beyond traditional bc implementations and the POSIX draft standard.  Command line
       options can cause these extensions to print a warning or to be rejected.  This document describes the language accepted  by  this
       processor.  Extensions will be identified as such.

答案3

另一种方法可能是将变量保存为整数,然后在最后将其转换为字符串:

A=12
B=$((A+1))
echo $B
13
C=$( printf '%04d' $B )
echo $C
0013

这种在数学中使用整数并转换为字符串作为答案的方式对我来说更直观,因为我习惯了 BASIC 编程。我很欣赏 Bash 没有像 C 和 BASIC 那样的变量类型,但假装它有让我很开心。

相关内容