예기치 않은 EOF 및 구문 오류

예기치 않은 EOF 및 구문 오류

현재 세 번째 쉘 스크립트를 작성 중인데 문제가 발생했습니다. 이것은 지금까지 내 스크립트입니다.

#!/bin/bash
echo "choose one of the following options : \
  1) display all current users \
  2) list all files \
  3) show calendar \
  4) exit script"

while read  
do  
 case in  
        1) who;;  
        2) ls -a;;  
        3) cal;;  
        4) exit;;  
 esac    
done

스크립트를 실행하려고 하면 다음과 같이 표시됩니다.

line2 : unexpected EOF while looking for matching '"'  
line14 : syntax error: unexpected end of file.    

내가 뭘 잘못했나요?

답변1

잊지 말자 select:

choices=( 
    "display all current users" 
    "list all files" 
    "show calendar" 
    "exit script"
)
PS3="your choice: "
select choice in "${choices[@]}"; do
    case $choice in
        "${choices[0]}") who;;
        "${choices[1]}") ls -a;;
        "${choices[2]}") cal;;
        "${choices[3]}") break;;
    esac
done

답변2

문제는 귀하의 case진술에 주어, 즉 평가해야 할 변수가 누락되어 있다는 것입니다. 따라서 다음과 같은 것을 원할 수도 있습니다.

#!/bin/bash
cat <<EOD
choose one of the following options:
1) display all current users
2) list all files
3) show calendar
4) exit script
EOD

while true; do
    printf "your choice: "
    read
    case $REPLY in
        1) who;;
        2) ls -a;;
        3) cal;;
        4) exit;;
    esac    
done

여기에는 case변수 이름이 지정되지 않은 경우 채워지는 기본 변수가 사용됩니다(자세한 내용 참조 $REPLY).readhelp read

또한 변경 사항에 유의하세요. printf각 라운드마다 프롬프트를 표시하고(새 줄을 추가하지 않음), cat여러 줄에 지침을 인쇄하여 줄바꿈하지 않고 읽기 쉽도록 했습니다.

답변3

먼저 단일 사례를 시도해 보겠습니다. 이를 사용하여 아래와 같이 read -p사용자 입력을 변수로 읽은 다음 Case 문을 읽습니다.opt

#!/bin/bash
read -p "choose one of the following options : \
  1) display all current users \
  2) list all files \
  3) show calendar \
  4) exit script" opt
case $opt in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac

위 스크립트는 잘 작동합니다. 이제 사용자가 옵션 4를 누를 때까지 사용자 입력을 읽을 수 있도록 루프에 넣어야 한다고 생각합니다.

그래서 우리는 while아래와 같은 루프를 사용하여 이를 수행할 수 있습니다. opt변수의 초기값을 0으로 설정했습니다 . 이제 변수 값이 0 while인 동안 opt루프를 반복합니다. 이것이 바로 opt명령문 끝에서 변수를 0으로 재설정하는 이유입니다 case.

#!/bin/bash
opt=0;
while [ "$opt" == 0 ]
do
read -p "choose one of the following options : \
  1) display all current users \
  2) list all files \
  3) show calendar \
  4) exit script" opt

case $opt in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
opt=0
done

답변4

개인적으로 나는 코드 시작 부분에 "while"을 넣을 것입니다. 그런 다음 이를 따라가면 :원하는 만큼 반복할 수 있습니다. 그것이 내가 쓴 방법입니다.

while :
do
    echo "choose one of the following options : \
      1) display all current users \
      2) list all files \
      3) show calendar \
      4) exit script"
    read string
    case $string in
        1)
            who
            ;;

그런 다음 계속 질문하고 마지막으로 마무리합니다.

esac
done

관련 정보