2017-07-28 79 views
1

我有一個平面文件稱爲項目,我想填充選擇,但我希望能夠一次選擇多個項目。項目bash一次選擇多個答案

文件內容:

cat 1 
dog 1 
pig 1 
cherry 2 
apple 2 

Basic腳本:

#!/bin/bash 
PS3=$'\n\nSelect the animals you like: ' 
options=$(grep '1' items|grep -v '^#' |awk '{ print $1 }') 

select choice in $options 
do 
    echo "you selected: $choice" 
done 

exit 0 

現在流動是我唯一可以在一次選擇一個選項的方式。我希望能夠回答1,3或1 3,並將它「您選擇:貓豬」迴應

謝謝

Tazmarine

+0

我會說這是不可能做到這一點與'select'。 –

回答

0

這是我想出了。這似乎符合我的要求。我想用逗號分隔的最終輸出:

#!/bin/bash 

newarray=(all $(grep '1' items|grep -v '^#' |awk '{ print $1 }')) 

options() { 
num=0 
for i in ${newarray[@]}; do 
    echo "$num) $i" 
    ((num++)) 
done 
} 

getanimal() { 
while [[ "$show_clean" =~ [A-Za-z] || -z "$show_clean" ]]; do 
    echo "What animal do you like: " 
    options 
    read -p 'Enter number: ' show 
    echo 
    show_clean=$(echo $show|sed 's/[,.:;]/ /g') 
    selected=$(\ 
    for s in $show_clean; do 
    echo -n "\${newarray[${s}]}," 
    done) 
    selected_clean=$(echo $selected|sed 's/,$//') 
done 
eval echo "You selected $selected_clean" 
} 

getanimal 

exit 0 
1

你不能這樣做,因爲這樣,但你可以隨時記錄每個個體的選擇:

#!/bin/bash 
PS3=$'\n\nSelect the animals you like: ' 
options=$(grep '1' items|grep -v '^#' |awk '{ print $1 }') 

# Array for storing the user's choices 
choices=() 

select choice in $options Finished 
do 
    # Stop choosing on this option 
    [[ $choice = Finished ]] && break 
    # Append the choice to the array 
    choices+=("$choice") 
    echo "$choice, got it. Any others?" 
done 

# Write out each choice 
printf "You selected the following: " 
for choice in "${choices[@]}" 
do 
    printf "%s " "$choice" 
done 
printf '\n' 

exit 0 

下面是一個例子互動:

$ ./myscript 
1) cat 
2) dog 
3) pig 
4) Finished 

Select the animals you like: 3 
pig, got it. Any others? 

Select the animals you like: 1 
cat, got it. Any others? 

Select the animals you like: 4 
You selected the following: pig cat 

如果改爲希望能夠在同一行上寫3 1,你必須使自己的菜單循環與echoread

+0

謝謝你的建議。我希望能夠使用1 3 4 7或1,3,4,7甚至1:3:4:7。有些列表可能有80多個項目較大,因此一次選擇一個列表並不是首選。我將不得不考慮這一點,併發布一些選項。由於項目列表可以改變我懷疑我會首先需要爲數字定義變量然後解析出來。我會在週二更新這篇文章,內容是我提出的。謝謝。 – tazmarine