)%20%E3%81%AF%E5%85%B7%E4%BD%93%E7%9A%84%E3%81%AB%E4%BD%95%E3%82%92%E3%81%99%E3%82%8B%E3%81%AE%E3%81%A7%E3%81%97%E3%82%87%E3%81%86%E3%81%8B%3F.png)
次の bash スクリプトは、2 進数を指定すると 10 進数を表示します。
echo $((2#$1))
正確にはなぜですか?
$1
それが入力であることは理解しています。おそらく2
ベース (バイナリ) です。しかし、使用されている構文が理解できません。
答え1
男の強打
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.
答え2
ドクターより:https://tiswww.case.edu/php/chet/bash/bashref.html#シェル演算
先頭に 0 が付いた定数は 8 進数として解釈されます。先頭に '0x' または '0X' が付いている場合は 16 進数を表します。それ以外の場合、数値は [base#]n の形式になります。ここで、オプションの base は算術基数を表す 2 から 64 までの 10 進数で、n はその基数の数です。base# を省略すると、基数 10 が使用されます。n を指定する場合、9 より大きい数字は小文字、大文字、'@'、および '_' の順序で表されます。基数が 36 以下の場合、小文字と大文字は 10 から 35 までの数値を表すために互換的に使用できます。
出力と出力echo $((16#FF))
255
echo $((2#0110))
6
答え3
イポールの答え素晴らしいですが、少し不完全です。bashのマニュアルページの引用部分では、構文は定数に対してのみ機能し、定数ではないと書かれています。[base#]n
2#$1
本当に動作します!
拡大
展開は、コマンド ラインが単語に分割された後に実行されます。実行される展開には、中括弧展開、チルダ展開、パラメーターと変数の展開、コマンド置換、算術展開、単語分割、パス名展開の 7 種類があります。
展開の順序は、中括弧展開、チルダ展開、パラメータと変数の展開、算術展開、コマンド置換(左から右に実行)、単語分割、パス名展開です。
基本的に、Bash は最初に変数の置換を実行し、 が$1
最初にその値に置き換えられます。その後で初めて算術展開が実行され、適切な定数のみが認識されます。