2013-04-04 87 views
13

我想在bash脚本中使用目录中的文件作为选项。用户应该能够选择一个,然后将所选文件的名称传递给变量。到目前为止,我可以得到文件列表,但几个小时后,我无法弄清楚如何显示它们作为选项。列出文件并使用bash在菜单中显示它们

#!/bin/bash 
prompt="Please select a file:" 
options=($(find -maxdepth 1 -print0 | xargs -0)) 

PS3="$prompt " 
select opt in "${options[@]}" "Quit"; do 

    case "$REPLY" in 
    for i in "${options[@]}" 
    do 
    $i') echo "You picked $opt which is file $REPLY";;' 
    done  
    $((${#options[@]}+1))) echo "Goodbye!"; break;; 
    *) echo "Invalid option. Try another one.";continue;; 

    esac 

done 

任何帮助,非常感谢。谢谢!

回答

20

我不认为case适合在这里:

#!/bin/bash 
prompt="Please select a file:" 
options=($(find -maxdepth 1 -print0 | xargs -0)) 

PS3="$prompt " 
select opt in "${options[@]}" "Quit" ; do 
    if ((REPLY == 1 + ${#options[@]})) ; then 
     exit 

    elif ((REPLY > 0 && REPLY <= ${#options[@]})) ; then 
     echo "You picked $opt which is file $REPLY" 
     break 

    else 
     echo "Invalid option. Try another one." 
    fi 
done  

ls -ld $opt 
+0

很好,谢谢! – castaway 2013-04-04 10:06:05

+0

我使用上面的代码出现错误。/home/RepLoqt#sh -x RevPrxyLogQuery.sh 'title ='反向代理日志查询工具(RepLoqt) 'prompt ='选择要查询的日志文件: ++ find ./logfiles -maxdepth 1 -print0 ++ xargs -0 + options ='(./logfiles ./logfiles/log_18-44 ./logfiles/log_18-3) '$'\ r''Reverse Proxy Log Query Tool(RepLoqt) everse Proxy Log查询工具(RepLoqt) 'PS3 ='选择您要查询的日志文件: 'evPrxyLogQuery.sh:第7行:语法错误附近的意外标记' 'evPrxyLogQuery.sh:第7行:'select opt in“$ {选项[@]}“”退出“; – antman1p 2015-10-26 16:36:34

+0

不要紧,因为某些原因,因为我在文件末尾加了.sh扩展名,它给了我那个错误。一旦我删除了扩展名,它工作...我不知道为什么。 – antman1p 2015-10-26 19:42:28

0

不要错过珀,FZY,smenu和朋友。他们会很高兴地从stdin中拿出一个带有交互式过滤器的用户友好选择菜单,然后再次将选定的线路输出。

相关问题