옵션이 목록의 내용이 되도록 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

관련 정보