echo $((2#$1)) 到底是做什么的?

Nan*_*ish 55 bash

以下 bash 脚本在给定二进制数时显示十进制数。

echo $((2#$1))
Run Code Online (Sandbox Code Playgroud)

为什么?

我明白这$1是输入。也许2是基础(二进制)。但我无法理解使用的语法。

Ipo*_*cer 75

男人 bash

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

[...]

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

[...]

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

  • -1 表示零解释。 (66认同)
  • `人bash | wc` 表示 [GNU bash, version 3.2.57] 手册页为 4890 行,**37094 个字**,329778 个字符。此答案将其缩减为仅 7 行、**176 个单词**、1115 个相关字符。我认为这个答案值得你点赞。(与此评论一样;-) (33认同)
  • 我认为这是很好的解释 (28认同)
  • 完全回答一个问题,即使“仅”通过整理现有文档,对我来说也不值得 -1。特别是如果该文档是 bash 的联机帮助页。 (19认同)
  • @MaxRied:-1 对您寻求不必要的绒毛的评论 (7认同)
  • 我没有投票,但是恕我直言,引用 `echo` 命令的解释是不必要的。 (4认同)
  • @BrunoBronosky 不知道你,但我的寻呼机已经搜索 / 键。 (2认同)
  • @Braiam,是的,`/2#` 给出了 0 个结果,但说真的,这不是辩论和 1337 主义的地方。我的评论旨在鼓励社区不要加剧分裂。SE 和 Reddit/4chan/etc 之间存在重要的文化差异。 (2认同)

小智 31

来自文档:https : //tiswww.case.edu/php/chet/bash/bashref.html#Shell-Arithmetic

带有前导 0 的常量被解释为八进制数。前导“0x”或“0X”表示十六进制。否则,数字采用 [base#]n 形式,其中可选基数是 2 到 64 之间的十进制数,表示算术基数,n 是该基数中的数字。如果省略 base#,则使用基数 10。指定 n 时,大于 9 的数字按小写字母、大写字母、“@”和“_”的顺序表示。如果基数小于或等于 36,小写和大写字母可以互换使用来表示 10 到 35 之间的数字。

所以echo $((16#FF))输出255echo $((2#0110))输出6


小智 25

Ipor 的回答非常好,但有点不完整。bash 手册页的引用部分指出该语法仅适用于常量,而不是常量。你应该问这是如何真正起作用的![base#]n2#$1

扩张

    拆分成单词后在命令行上进行扩展。执行的扩展有七种:大括号扩展、波浪号扩展、参数和变量扩展、命令替换、算术扩展、分词和路径名扩展。

    展开的顺序是:大括号展开;波浪号扩展、参数和变量扩展、算术扩展和命令替换(以从左到右的方式完成);分词;和路径名扩展。

基本上 Bash 首先进行变量替换,因此$1首先用它的值替换。只有这样它才进行算术展开,它只看到一个适当的常数。

  • +1 因为理解扩展顺序对于理解许多不同的 Bash 表达式非常有用。 (8认同)
  • “请注意,在计算算术表达式之前,参数 `$1` 会扩展为生成整数常量。请参阅 https://www.gnu.org/software/bash/manual/bash.txt,第 3.5 节” (2认同)