不正な番号: {1..3} が表示されるのはなぜですか?

不正な番号: {1..3} が表示されるのはなぜですか?

なぜ私は

./6_sum_square_difference.sh: 11: ./6_sum_square_difference.sh: Illegal number: {1..3}

のために

#!/bin/sh
summing () {
  the_total=0
  num_in=$1
  for one_num in {1..$num_in}
  do  
    printf "aaaa\n"
    the_total=$((the_total+one_num)) # <-- Line 11
  done
}
summing 3
if [[ $the_total == 6 ]]; then
  echo "equa to 6 "$the_total
else
  echo "NOT equal to 6"
fi
printf "total= "$the_total

答え1

{1..$num_in}は kshism/zshism です。次のように書く必要があります。

`seq $num_in`

注: bash は のようなコードをサポートしていますが{1..3}、コメントで 1_CR が述べているように、{1..$num_in}括弧の展開がパラメータの置換に先行するため、bash では動作しません。したがって、これはおそらく ksh93 または zsh から来ており、パラメータの展開が最初に行われるため動作します。

答え2

{1..$num_in}は数値のシーケンスに展開されず、 などのリテラル文字列にのみ展開されます{1..1}。そのため{1..2}、スクリプトは算術展開を実行し、無効な数値を検出し、エラー メッセージを出力します。

shebang を として使用する場合#!/bin/sh、スクリプトを実行するためにリンクされているシェルが使用されるかどうかはシステムによって異なります/bin/sh。したがって、エラー メッセージはシェルに応じて異なる場合があります。

dash

$ dash test.sh 
aaaa
test.sh: 74: test.sh: Illegal number: {1..3}

bash

$ bash test.sh 
aaaa
test.sh: line 74: {1..3}: syntax error: operand expected (error token is "{1..3}")
NOT equal to 6
total= 0

およびpdkshmksh:

$ pdksh test.sh 
aaaa
test.sh[77]: {1..3}: unexpected '{'
NOT equal to 6
total= 0

yash

$ yash test.sh 
aaaa
yash: arithmetic: `{1..3}' is not a valid number

poshセグメンテーション違反があっても:

$ posh test.sh 
aaaa
test.sh:77: {1..3}: unexpected `{'
Segmentation fault

このスクリプトは および で動作しzshますksh93:

$ zsh test.sh 
aaaa
aaaa
aaaa
equa to 6 6
total= 6

関連情報