BASH脚本:whiptail文件选择
我发现了一个很棒的小程序,可以让我在我的
Bash Scripts中添加用户友好的GUI;
鞭尾 然而,whiptail man page并不是那么有用,也没有提供任何示例.在做了一些谷歌搜索后,我了解如何使用whiptail创建一个简单的是/否菜单: #! /bin/bash # http://archives.seul.org/seul/project/Feb-1998/msg00069.html if (whiptail --title "PPP Configuration" --backtitle "Welcome to SEUL" --yesno " Do you want to configure your PPP connection?" 10 40 ) then echo -e "nWell,you better get busy!n" elif (whiptail --title "PPP Configuration" --backtitle "Welcome to SEUL" --yesno " Are you sure?" 7 40) then echo -e "nGood,because I can't do that yet!n" else echo -e "nToo bad,I can't do that yetn" fi 但我真的想建立一个文件选择菜单使用whiptail来替换我在一些不同的备份/恢复bash脚本中的旧代码: #!/bin/bash #This script allows you to select a file ending in the .tgz extension (in the current directory) echo "Please Select the RESTORE FILE you would like to restore: " select RESTOREFILE in *.tgz; do break #Nothing done echo "The Restore File you selected was: ${RESTOREFILE}" 我认为这必须通过whiptail的’–menu’选项完成,但我不确定如何去做?
构建一个文件名和菜单选择标记数组:
i=0 s=65 # decimal ASCII "A" for f in *.tgz do # convert to octal then ASCII character for selection tag files[i]=$(echo -en " $(( $s / 64 * 100 + $s % 64 / 8 * 10 + $s % 8 ))") files[i+1]="$f" # save file name ((i+=2)) ((s++)) done 即使存在带空格的文件名,这样的方法也能正常工作.如果文件数量很大,您可能需要设计另一个标记策略. 使用标记的字母字符可以按一个字母跳转到该项目.数字标签似乎没有这样做.如果您不需要这种行为,那么您可以消除一些复杂性. 显示菜单: whiptail --backtitle "Welcome to SEUL" --title "Restore Files" --menu "Please select the file to restore" 14 40 6 "${files[@]}" 如果退出代码为255,则取消对话框. if [[ $? == 255 ]] then do cancel stuff fi 要捕获变量中的选择,请使用此结构(将whiptail命令替换为“whiptail-command”): result=$(whiptail-command 2>&1 >/dev/tty) 要么 result=$(whiptail-command 3>&2 2>&1 1>&3-) 变量$result将包含与数组中的文件对应的字母表字母.不幸的是,版本4之前的Bash不支持关联数组.您可以从这样的字母计算文件数组的索引(注意“额外”单引号): ((index = 2 * ( $( printf "%d" "'$result" ) - 65 ) + 1 )) 例: Welcome to SEUL ┌──────────┤ Restore Files ├───────────┐ │ Please select the file to restore │ │ │ │ A one.tgz ↑ │ │ B two.tgz ? │ │ C three.tgz ? │ │ D another.tgz ? │ │ E more.tgz ? │ │ F sp ac es.tgz ↓ │ │ │ │ │ │ <Ok> <Cancel> │ │ │ └──────────────────────────────────────┘ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |