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


16

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

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

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

我已经四处搜寻,无法解释,也无法弄清楚如何增加数字。(我实际上想以B =“ 0013”结尾,并且每次将其用作备份前缀时都加1)


2
提防本质上源自UNIX的任何语言的前导零。这通常表示八进制。
约书亚

不,您不是,您会得到1011二进制文件
Ken Mollerup

Answers:


28

这是因为以开头的数字0被视为八进制bash,因此它正在做八进制(基数8)加法。要获得此结构的十进制加法,您需要显式定义Base或不一起使用00

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

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

5

您可以尝试使用以下命令获得答案:

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.

4
echo可以使用Bash的“此处字符串”语法代替使用和管道。效果是一样的,但是恕我直言,“这里的字符串”更漂亮: bc <<< "$A + 1":-)
Byte Commander

bc除了here链接之外,对命令进行一两句话的介绍也会很有帮助。
WinEunuuchs2Unix

2

另一种方法是将变量保留为整数,并在最后将它们转换为字符串:

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

在我习惯于BASIC编程时,这种在数学中使用整数并将其转换为答案的字符串的方式对我来说更加直观。我很欣赏Bash没有像C和BASIC这样的变量类型,但是假装它确实让我高兴。


这是一个测试,以突出我遇到的问题。我通过获取另一个命令的输出来读取初始变量,该命令是文本并且具有前导零。
罗伯特3452年

啊...历史总是说明我们如何到达现在。
WinEunuuchs2Unix

@ Robert3452您也可以删除前导零:A="0012"; A=$((10#$A))
wjandrea
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.