잘못된 번호를 받는 이유: {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`

참고: 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

관련 정보