옵션이 목록의 내용이 되도록 bash 메뉴 스크립트를 어떻게 작성합니까?

옵션이 목록의 내용이 되도록 bash 메뉴 스크립트를 어떻게 작성합니까?

저는 일반적인 bash 메뉴 스크립트를 사용하고 있습니다.

#!/bin/bash
# Bash Menu Script Example

PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 3")
            echo "you chose choice 3"
            ;;
        "Quit")
            break
            ;;
    esac
done

실행되면 다음과 같이 읽습니다.

1) Option 1
2) Option 2
3) Option 3
4) Quit
Please enter your choice: 

list.txt라는 파일이 있습니다.

Android
iOS
Windows

옵션이 list.txt의 내용이 되도록 bash 메뉴 스크립트를 어떻게 작성합니까?

1) Android
2) iOS
3) Windows
4) Quit
Please enter your choice: 

답변1

당신은 대체할 수 있습니다

options=("Option 1" "Option 2" "Option 3" "Quit")

~와 함께

mapfile -t options < list.txt
options+=( "Quit" )

패턴을 조정하세요 case. 선택한 숫자를 포함하고 확인하기 더 쉬운 변수 의 내용을 테스트하는 대신 $opt사용할 수 있습니다 .$REPLY

답변2

파일을 배열로 읽어옵니다.

#!/usr/bin/env bash

readarray -t list < list.txt

PS3='Please enter your choice or 0 to exit: '
select selection in "${list[@]}"; do
    if [[ $REPLY == "0" ]]; then
        echo 'Goodbye' >&2
        exit
    else
       echo $REPLY $selection
        break
    fi
done

관련 정보