列出文件并使用 bash 在菜单中显示它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15807845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List files and show them in a menu with bash
提问by castaway
I am trying to use the files in a directory as options in a bash script. The user should be able to select one and then pass the name of the selected file into a variable. So far I can get the list of files, but after a few hours trying I can't figure out how to show them as options.
我正在尝试将目录中的文件用作 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
Any help is much appreciated. Thanks!
任何帮助深表感谢。谢谢!
回答by choroba
I do not think caseis suitable here:
我认为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
回答by eMPee584
Don't miss percol, fzy, smenu and friends. They'll happily take from stdin, present a user-friendly select menu with interactive filter, then pipe selected lines out again.
不要错过 percol、fzy、smenu 和朋友。他们会很高兴地从标准输入中获取,呈现一个带有交互式过滤器的用户友好的选择菜单,然后再次将选定的行输出。

