echo $ ((2 # $ 1)) 정확히 무엇을합니까? 스크립트는 2 진 숫자가 제공 될 때

다음 bash 스크립트는 2 진 숫자가 제공 될 때 10 진수를 표시합니다.

echo $((2#$1))

왜 정확히?

나는 그것이 $1입력 이라는 것을 이해합니다 . 아마도 2기본 (이진) 일 수 있습니다. 그러나 사용 된 구문을 이해할 수 없습니다.



답변

남자 배쉬

   echo [-neE] [arg ...]
          Output  the  args,  separated  by spaces, followed by a newline.
          The return status is 0 unless a write error occurs.   If  -n  is
          specified, the trailing newline is suppressed.  If the -e option
          is given,  interpretation  of  the  following  backslash-escaped
          characters  is  enabled.

[…]

   Arithmetic Expansion
       Arithmetic  expansion allows the evaluation of an arithmetic expression
       and the substitution of the result.  The format for  arithmetic  expan‐
       sion is:

              $((expression))

[…]

   Constants with a leading 0 are interpreted as octal numbers.  A leading
   0x or  0X  denotes  hexadecimal.   Otherwise,  numbers  take  the  form
   [base#]n,  where the optional base is a decimal number between 2 and 64
   representing the arithmetic base, and n is a number in that  base.   If
   base#  is omitted, then base 10 is used.  When specifying n, the digits
   greater than 9 are represented by the lowercase letters, the  uppercase
   letters, @, and _, in that order.  If base is less than or equal to 36,
   lowercase and uppercase letters may be used interchangeably  to  repre‐
   sent numbers between 10 and 35.


답변

다음 문서에서 https://tiswww.case.edu/php/chet/bash/bashref.html#Shell-Arithmetic

앞에 0이있는 상수는 8 진수로 해석됩니다. 선행 ‘0x’또는 ‘0X’는 16 진수를 나타냅니다. 그렇지 않은 경우 숫자는 [base #] n 형식을 취합니다. 여기서 선택적 기준은 산술 기준을 나타내는 2에서 64 사이의 10 진수이며 n은 해당 기준의 숫자입니다. base #가 생략되면 base 10이 사용됩니다. n을 지정할 때 9보다 큰 숫자는 소문자, 대문자 ‘@’및 ‘_’의 순서로 표시됩니다. 밑이 36보다 작거나 같은 경우 소문자와 대문자를 서로 바꿔서 사용하여 10에서 35 사이의 숫자를 나타낼 수 있습니다.

그래서 echo $((16#FF))출력 255echo $((2#0110))출력6


답변

아이포의 대답 은 훌륭하지만 약간 불완전합니다. bash 매뉴얼 페이지의 인용 부분에는 구문이 상수에만 적용되며 상수 는 아니라고 명시되어 있습니다. 이것이 실제로 어떻게 작동 하는지 물어봐야 합니다![base#]n2#$1

확장

    확장은 단어로 분할 된 후 명령 행에서 수행됩니다. 괄호 확장, 물결 확장, 매개 변수 및 변수 확장, 명령 대체, 산술 확장, 단어 분할 및 경로 이름 확장의 7 가지 확장이 수행됩니다.

    확장 순서는 다음과 같습니다. 괄호 확장; 물결표 확장, 매개 변수 및 변수 확장, 산술 확장 및 명령 대체 (왼쪽에서 오른쪽으로 수행); 단어 분할; 경로명 확장.

기본적으로 Bash는 변수 대체를 먼저 수행하므로 $1먼저 값을 대체합니다. 그런 다음에 만 산술 확장을 수행하여 적절한 상수 만 봅니다.


답변