BASH脚本:whiptail文件选择

前端之家收集整理的这篇文章主要介绍了BASH脚本:whiptail文件选择前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现了一个很棒的小程序,可以让我在我的 Bash Scripts中添加用户友好的GUI;

鞭尾

然而,whiptail man page并不是那么有用,也没有提供任何示例.在做了一些谷歌搜索后,我了解如何使用whiptail创建一个简单的是/否菜单

  1. #! /bin/bash
  2. # http://archives.seul.org/seul/project/Feb-1998/msg00069.html
  3. if (whiptail --title "PPP Configuration" --backtitle "Welcome to SEUL" --yesno "
  4. Do you want to configure your PPP connection?" 10 40 )
  5. then
  6. echo -e "\nWell,you better get busy!\n"
  7. elif (whiptail --title "PPP Configuration" --backtitle "Welcome to
  8. SEUL" --yesno " Are you sure?" 7 40)
  9. then
  10. echo -e "\nGood,because I can't do that yet!\n"
  11. else
  12. echo -e "\nToo bad,I can't do that yet\n"
  13. fi

但我真的想建立一个文件选择菜单使用whiptail来替换我在一些不同的备份/恢复bash脚本中的旧代码

  1. #!/bin/bash
  2. #This script allows you to select a file ending in the .tgz extension (in the current directory)
  3. echo "Please Select the RESTORE FILE you would like to restore: "
  4. select RESTOREFILE in *.tgz; do
  5. break #Nothing
  6. done
  7. echo "The Restore File you selected was: ${RESTOREFILE}"

我认为这必须通过whiptail的’–menu’选项完成,但我不确定如何去做?
有什么指针吗?
或者你能指出我的一些wh examples的例子吗?

构建一个文件名和菜单选择标记数组:
  1. i=0
  2. s=65 # decimal ASCII "A"
  3. for f in *.tgz
  4. do
  5. # convert to octal then ASCII character for selection tag
  6. files[i]=$(echo -en "\0$(( $s / 64 * 100 + $s % 64 / 8 * 10 + $s % 8 ))")
  7. files[i+1]="$f" # save file name
  8. ((i+=2))
  9. ((s++))
  10. done

即使存在带空格的文件名,这样的方法也能正常工作.如果文件数量很大,您可能需要设计另一个标记策略.

使用标记的字母字符可以按一个字母跳转到该项目.数字标签似乎没有这样做.如果您不需要这种行为,那么您可以消除一些复杂性.

显示菜单

  1. whiptail --backtitle "Welcome to SEUL" --title "Restore Files" \
  2. --menu "Please select the file to restore" 14 40 6 "${files[@]}"

如果退出代码为255,则取消对话框.

  1. if [[ $? == 255 ]]
  2. then
  3. do cancel stuff
  4. fi

要捕获变量中的选择,请使用此结构(将whiptail命令替换为“whiptail-command”):

  1. result=$(whiptail-command 2>&1 >/dev/tty)

要么

  1. result=$(whiptail-command 3>&2 2>&1 1>&3-)

变量$result将包含与数组中的文件对应的字母表字母.不幸的是,版本4之前的Bash不支持关联数组.您可以从这样的字母计算文件数组的索引(注意“额外”单引号):

  1. ((index = 2 * ( $( printf "%d" "'$result" ) - 65 ) + 1 ))

例:

  1. Welcome to SEUL
  2. ┌──────────┤ Restore Files ├───────────┐
  3. Please select the file to restore
  4. A one.tgz
  5. B two.tgz
  6. C three.tgz
  7. D another.tgz
  8. E more.tgz
  9. F sp ac es.tgz
  10. <Ok> <Cancel>
  11. └──────────────────────────────────────┘

猜你在找的Bash相关文章