Bash YAD按钮可以调用脚本中的函数吗?
我在BASH中玩YAD对话框,在按钮构造方面遇到了问题。我无法使用YAD按钮调用同一脚本中的函数。有办法做到这一点吗 我的理解是,如果我使用以下结构,按下按钮将调用冒号后面的命令。如果用户单击“打开浏览器”按钮,此示例将打开Firefox实例: 我有一个带有几个BASH函数的脚本。我想按一下按钮调用其中一个函数。没有。以下是一个简单的脚本,它在运行时演示了令人失望的行为:Bash YAD按钮可以调用脚本中的函数吗?,bash,yad,Bash,Yad,我在BASH中玩YAD对话框,在按钮构造方面遇到了问题。我无法使用YAD按钮调用同一脚本中的函数。有办法做到这一点吗 我的理解是,如果我使用以下结构,按下按钮将调用冒号后面的命令。如果用户单击“打开浏览器”按钮,此示例将打开Firefox实例: 我有一个带有几个BASH函数的脚本。我想按一下按钮调用其中一个函数。没有。以下是一个简单的脚本,它在运行时演示了令人失望的行为: #!/bin/bash, click_one() { yad --center --text="Clicked th
#!/bin/bash,
click_one()
{
yad --center --text="Clicked the one"
}
click_two()
{
yad --center --text="Clicked the two"
}
cmd="yad --center --text=\"Click a button to see what happens\" \
--button=\"One\":click_one \
--button=\"Two\":2 \
--button=\"Date\":date \
--button=\"Exit\":99"
proceed=true
while $proceed; do
eval "$cmd"
exval=$?
case $exval in
2) click_two;;
99) proceed=false;;
esac
done
在上面的代码中,按钮Date按预期工作,调用Date命令。按钮2和Exit起作用,因为我正在检查命令的Exit值并根据其值进行分支。遗憾的是,按钮一什么也不做。我曾希望单击按钮1可以调用本地函数click\u One。我想知道是否有办法格式化YAD命令,以便调用click_one函数
虽然上面的代码建议使用exit值来解决问题,但我真正的目标是对一个表单按钮应用一个成功的答案,据我目前所知,它不会返回exit值。换句话说,以下操作也会以静默方式失败,但我希望它调用函数click\u one:
显然不是,它需要一个实际的命令 您可以:将函数放在一个单独的文件中,并作为命令启动bash,获取该文件的源代码,然后调用该函数 在这里,我还将重新构造代码以将yad命令存储在数组中。这将使脚本更加健壮:
# using an array makes the quoting a whole lot easier
cmd=(
yad --center --text="Click a button to see what happens"
--button="One":"bash -c 'source /path/to/functions.sh; click_one'"
--button="Two":2
--button="Date":date
--button="Exit":99
)
while true; do
"${cmd[@]}" # this is how to invoke the command from the array
exval=$?
case $exval in
2) click_two;;
99) break;;
esac
done
一种可能的方式:
#!/bin/bash
click_one(){
yad --center --text="Clicked the one"
}
click_two(){
yad --center --text="Clicked the two"
}
export -f click_one click_two
yad \
--title "My Title" \
--center --text="Click a button to see what happens" \
--button="One":"bash -c click_one" \
--button="Two":"bash -c click_two" \
--button="Date":"date" \
--button="Exit":0
echo $?
这个答案和@kyodev的答案都包含了解决方案的一部分,使用bash-c click_one。缺少的是我应该导出函数,以便从yad控件访问它们。在我的最终版本中,我在while循环之前添加了export-f click\u one和export-f click\u two,然后取消设置click\u one和unset click\u two after,以防止脚本结束后函数可用+1建议使用命令数组,这是我以前不熟悉的构造。
# using an array makes the quoting a whole lot easier
cmd=(
yad --center --text="Click a button to see what happens"
--button="One":"bash -c 'source /path/to/functions.sh; click_one'"
--button="Two":2
--button="Date":date
--button="Exit":99
)
while true; do
"${cmd[@]}" # this is how to invoke the command from the array
exval=$?
case $exval in
2) click_two;;
99) break;;
esac
done
#!/bin/bash
click_one(){
yad --center --text="Clicked the one"
}
click_two(){
yad --center --text="Clicked the two"
}
export -f click_one click_two
yad \
--title "My Title" \
--center --text="Click a button to see what happens" \
--button="One":"bash -c click_one" \
--button="Two":"bash -c click_two" \
--button="Date":"date" \
--button="Exit":0
echo $?