변수에 1을 추가하면 예상대로 작동하지 않습니다 (배시 산술)


16

bash 터미널에 다음을 쓰면 :

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

나는 예상대로 11이 아니라 13을 얻습니다 !!!!!

나는 구글을 둘러 보았고 전혀 설명 할 수 없거나 숫자를 증가시키는 방법을 연구했다. (실제로 B = "0013"으로 끝나고 이것을 백업의 접두사로 사용할 때마다 하나씩 증가시키고 싶습니다)


2
기본적으로 UNIX에서 시작된 모든 언어에서 선행 0을주의하십시오. 이것은 일반적으로 8 진을 의미합니다.
Joshua

아니 당신은 1011 바이너리를 얻을 수 없습니다
Ken Mollerup

답변:


28

로 시작하는 숫자 0는에 의해 8 진수로 취급 bash되기 때문에 8 진수 (기본 8) 추가를 수행하기 때문입니다. 이 구조에 10 진수를 더하려면 기본을 명시 적으로 정의하거나 전혀 사용하지 않아야 00합니다.

10 진수의 경우 밑이 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의 "here string"구문을 사용할 수 있습니다. 효과는 동일하지만 IMHO "여기에서 문자열"이 더 아름답습니다. bc <<< "$A + 1":-)
바이트 사령관

링크 bc외에 명령에 대한 한두 문장 소개 here가 도움이 될 것입니다.
WinEunuuchs2Unix

2

다른 방법은 변수를 정수로 유지하고 마지막에 문자열로 변환하는 것입니다.

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

수학에서 정수로 작업하고 답을 위해 문자열로 변환하는이 스타일은 기본 프로그래밍에 익숙해지기 때문에 더 직관적입니다. Bash에는 C 및 BASIC과 같은 변수 유형이 없지만 척하는 것이 행복합니다.


이것은 내가 겪고있는 문제를 강조하기위한 테스트였습니다. 텍스트이고 앞에 0이있는 다른 명령의 출력을 취하여 초기 변수를 읽습니다.
Robert3452

아 .. 역사는 항상 우리가 현재에 어떻게 도달했는지 설명합니다.
WinEunuuchs2Unix

@ Robert3452 또한 선행 0을 제거 할 수 있습니다.A="0012"; A=$((10#$A))
wjandrea
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.