違法な番号を受け取るのはなぜですか? {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}クシズム/ズシズムです。次のように書く必要があります。

`seq $num_in`

{1..3}注:bashはコメント内の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

関連情報