当前位置: 首页>>技术教程>>正文


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

问题描述

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

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

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

我已经在 Google 上搜索过了,但根本无法解释,也无法弄清楚如何让这个数字增加。\n(我实际上希望以 B=”0013″ 结束,并且每次都增加一,因为我使用它作为备份的前缀)

最佳办法

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

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

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

次佳办法

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

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

有关 bc 命令的更多信息,请参阅 here

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.

第三种办法

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

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

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

参考资料

本文由Ubuntu问答整理, 博文地址: https://ubuntuqa.com/article/14517.html,未经允许,请勿转载。