如何解决捕获嵌入在 bash 函数中的对话调用的结果
我想从 bash 的通用函数中调用 unix dialog
编辑框。我感兴趣的两个结果是:
- 如果用户点击确定,我想捕获用户在编辑框中输入的内容
- 检测用户是否点击了取消
这是我的一些代码,但我不确定这是否是最好的方法:
function ib_generic()
{
tmp_file="/tmp/file.tmp"
if [ -f $tmp_file ]
then
rm -f $tmp_file
fi
mkfifo $tmp_file
# push the user input to $tmp_file
dialog --stdout \
--title "$1" \
--backtitle "My Backtitle" \
--inputbox "$2" 20 40 2> $tmp_file &
# detect 'cancel' or 'escape':
if [[ $? -eq 0 || $? -eq 255 ]]
then
rm -f $tmp_file
echo 1
else # 'ok' was pressed so proceed:
result="$( cat /tmp/file.tmp )"
rm -f $tmp_file
echo $result
fi
}
如果点击 OK,取消结果的最佳方法是什么,如果没有,如何检测 Cancel 或 Escape?
解决方法
不要在后台运行 dialog
,因为它不会等待它完成并且不会设置 $?
。
您的退出状态也有误。 0
表示 OK
被按下,1
表示 Cancel
,255
表示 Escape
。
dialog --stdout \
--title "$1" \
--backtitle "My Backtitle" \
--inputbox "$2" 20 40 2> "$tmp_file"
exit=$?
if [ $exit -eq 0 ] # OK was pressed
then
echo "$result"
elif [ $exit -eq 1 ] || [ $exit -eq 255 ] # Cancel or Escape was pressed
then
echo 1
else
echo 2
fi
有一个更完整的例子here
,对话框在每个按钮上返回不同的退出代码,这是我的做法:
input=$(
dialog --stdout \
--title "test" \
--backtitle "My Backtitle" \
--inputbox "$2" 20 40
)
case $? in
0) echo "ok $input";;
1) echo 'cancel' ;;
2) echo 'help' ;;
3) echo 'extra' ;;
255) echo 'esc' ;;
esac
更多信息是here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。