bash脚本-读取单个击键,包括特殊键Enter和空格 [英] bash scripting - read single keystroke including special keys enter and space

查看:102
本文介绍了bash脚本-读取单个击键,包括特殊键Enter和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定是否应该将其放在stackoverflow或unix.stackexchange上,但是我发现了一些问题在这里,就这样

Not sure if I should put this on stackoverflow or unix.stackexchange but I found some similar questions here, so here it goes.

我正在尝试创建一个由.bashrc调用的脚本,该脚本允许我根据单个击键选择两个选项之一.通常这并不难,但是我希望与这两个选项相对应的两个键为空格键并输入.

I'm trying to create a script to be called by .bashrc that allows me to select one of two options based on a single keystroke. That wouldn't be hard normally but I want the two keys corresponding to the two options to be space and enter.

这是我到目前为止所得到的:

Here's what I got so far:

#!/bin/bash

SELECT=""
while [[ "$SELECT" != $'\x0a' && "$SELECT" != $'\x20' ]]; do
    echo "Select session type:"
    echo "Press <Enter> to do foo"
    echo "Press <Space> to do bar"
    read -s -N 1 SELECT
    echo "Debug/$SELECT/${#SELECT}"
    [[ "$SELECT" == $'\x0a' ]] && echo "enter" # do foo
    [[ "$SELECT" == $'\x20' ]] && echo "space" # do bar
done

如果按回车键,空格键,退格键和x键,我将得到以下输出:

The following output is what I get if I press enter, space, backspace and x:

:~$ bin/sessionSelect.sh
Select session type:
Press <Enter> to start/resume a screen session
Press <Space> for a regular ssh session
Debug//0
Select session type:
Press <Enter> to start/resume a screen session
Press <Space> for a regular ssh session
Debug//0
Select session type:
Press <Enter> to start/resume a screen session
Press <Space> for a regular ssh session
Debug//1
Select session type:
Press <Enter> to start/resume a screen session
Press <Space> for a regular ssh session
Debug/x/1

因此,输入和空格都将导致空的SELECT.没办法区分两者.我试图将-d'D'添加到读取选项,但这没有帮助.也许有人可以指出我正确的方向.

So both enter and space result in an empty SELECT. No way to distinguish the two. I tried to add -d 'D' to the read options, but that didn't help. Maybe someone can point me in the right direction.

bash版本为4.2 btw.

The bash version would be 4.2 btw.

推荐答案

尝试将读取定界符设置为空字符串,然后检查内置的$ REPLY变量:

Try setting the read delimiter to an empty string then check the builtin $REPLY variable:

read -d'' -s -n1

由于某种原因,我无法使它正常工作以指定变量.

For some reason I couldn't get it to work specifying a variable.

这篇关于bash脚本-读取单个击键,包括特殊键Enter和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆