為什麼我收到非法號碼:{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連結到哪個 shell 來執行腳本。因此,錯誤訊息可能會根據 shell 的不同而有所不同。

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

相關內容