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

Rob*_*452 16 bash

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

A="0012"
B=$((A+1))
echo $B
Run Code Online (Sandbox Code Playgroud)

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

我已经用谷歌搜索了,我根本无法解释它,或者弄清楚如何使数字递增。(我实际上想以 B="0013" 结尾并每次递增 1,因为我将其用作备份的前缀)

hee*_*ayl 28

那是因为以 开头的数字0被视为八进制bash,因此它正在执行八进制(基数 8)加法。要获得此结构的 Decimal 加法,您需要明确定义 Base 或00完全不使用。

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

$ A="10#0012"
$ echo $((A+1))
13
Run Code Online (Sandbox Code Playgroud)


sno*_*oop 5

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

A="0012"
echo $A + 1 | bc
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 Bash 的“here string”语法,而不是使用 `echo` 和管道。效果是一样的,但恕我直言,“这里的字符串”更漂亮:`bc <<< "$A + 1"` :-) (4认同)