如何編寫 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

如何編寫 bash 選單腳本,使選項成為 list.txt 的內容:

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

相關內容