2017-07-28 41 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