gpt4 book ai didi

BASH 脚本 : whiptail file select

转载 作者:行者123 更新时间:2023-11-29 08:59:29 30 4
gpt4 key购买 nike

我找到了一个很棒的小程序,可以让我将用户友好的 GUI 添加到我的 Bash 脚本中;

鞭尾

然而 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 yet\n"
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 "\0$(( $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> │
│ │
└──────────────────────────────────────┘

关于BASH 脚本 : whiptail file select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562666/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com