gpt4 book ai didi

bash 脚本案例语句无法使用对话框

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

我最近一直在试验对话和 bash 脚本。我创建了一个包含三个选项的对话框菜单:用户、密码和组,然后还有一个退出选项。我试图在一个 case 语句中为每个函数运行函数,但它似乎总是落入 catchall 最后一个语句并输出 echo "Something Else..."语句,无论我选择哪个选项而不是说运行相关函数中的 echo 语句,例如echo "进入用户子菜单"

我试过在调试时运行它:

bash -x myscript

我得到以下输出:

+ choice='Users
Error: Expected a box option.
Use --help to list options.'
+ '[' 'Users
Error: Expected a box option.
Use --help to list options.' '!=' ' Quit ']'
+ case $choice in
+ echo 'Something else. Where Am I?'
Something else. Where Am I?
+ exit 0

我仍在尝试弄清楚“Expected a box option”是什么意思,这听起来像是与对话框有关,但我也想知道我的 if 语句或 bash 中的 case 语句是否有问题。

我的脚本代码:

#!/bin/bash

function quit {
exit 0
}

function menu {

choice=$(dialog --backtitle "Rob Graves's Bash Scripting" \
--title "Main Menu" --menu "Choose one" 30 50 4 "Users" \
"- Do something with users" "Passwords"\
"- Do stuff with passwords" "Groups" "- Do things with groups" \
"Quit" "- Exit to desktop" --clear --nocancel 3>&1 1>&2 2>&3)

if [ "$choice" != "Quit" ]; then

case $choice in
Users)
users #calls users function
;;
Passwords)
passwords #calls passwords function
;;
Groups)
groups #calls groups function
;;
*)
echo "Something else. Where Am I?"
;;
esac

else
echo "Quitting..."
quit
fi

}

function users {
echo "Entering Users sub-menu"
}

function passwords {
echo "Entering Passwords sub-menu "
}

function groups {
echo "Entering Groups sub-menu"

menu

exit 0

最佳答案

您的直接选择似乎是 dialog命令喜欢选项--clear--nocancel正如您所提到的,最后的选项。重新排序似乎按预期工作正常

choice=$(dialog --backtitle "Rob Graves's Bash Scripting" \
--title "Main Menu" \
--clear \
--nocancel \
--menu "Choose one" 30 50 4 \
"Users" "- Do something with users" \
"Passwords" "- Do stuff with passwords" \
"Groups" "- Do things with groups" \
"Quit" "- Exit to desktop" 3>&1 1>&2 2>&3)

此外,始终引用您的 case 也是个好主意选项字符串如下

case "$choice" in
"Users")
users #calls users function
;;
"Passwords")
passwords #calls passwords function
;;
"Groups")
groups #calls groups function
;;
*)
echo "Something else. Where Am I?"
esac

另请记住,您还可以为 "Users" 添加选项作为"1 - Users"dialog菜单和 case菜单如下。

enter image description here

并在case声明为

case "$choice" in
"1 - Users")

另请注意命令 users(1)groups(1)是作为 GNU 的一部分可用的标准命令 bash对函数使用相同的名称有可能带来不确定性。始终选择明确的名称。

请记住在脚本失败时使用非零退出代码退出脚本。例如在上面的默认情况下,记得添加一个 exit 1 , 因此它添加了另一种调试工具的方式来查看,当脚本异常退出时,运行预期的序列流。

    *)
echo "Something else. Where Am I?"
exit 1
;;

当它被击中并且当你的脚本退出并执行 echo $? 时会显示返回的代码。

同时删除非标准 function来自脚本中函数定义的关键字。只要脚本在 bash 中运行shell 它应该没问题,在纯 POSIX only shell 上,可能无法识别关键字。

您还应该使用 #!/usr/bin/env bash 对于 portability : 不同的 *nixes put bash在不同的地方,并使用 /usr/bin/env是运行第一个 bash 的解决方法在 PATH 上找到.

关于bash 脚本案例语句无法使用对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55638082/

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