首页 > 解决方案 > 使用两个分隔符中的任何一个终止读取(即 read -d '.' -> read -d '[Ee]')

问题描述

我正在编写一个 shell 脚本,用户应该在其中输入一个字符串(后跟 enter),并且有一些字符会立即终止“读取”命令。我做了研究,发现了这个:

read -d '.'

所以这意味着读命令将在'.'时终止。被输入。所以我可以输入

Hello, this is the user's input.

当输入点时,“读取”将终止。

但我需要这个有不同的分隔符。当用户输入例如“E”或“e”时,我需要一种方法来终止“读取”。我用通配符试过了:

read -d [E,e]

但是,'[' 是终止分隔符。'read' 忽略 'E' 和 'e',但在输入 '[' 时终止。

我还尝试了几个“-d”标志:

read -d 'E' -d 'e'

但似乎第二个“-d”覆盖了第一个。只是 'e' 是作为终止分隔符的标记,'E' 被忽略。

我能做些什么?“读取”或其他命令是否还有其他可能性?

标签: bashshell

解决方案


string=''
store_IFS="$IFS"                # Storing current IFS value
IFS=                            # Setting IFS to Null to space characters to enter
while true              
do
    read -sn 1 k                 # -n for reading byte by byte  and -s is to suppress the printing of input.

    if [ "$k" = $'\177' ] && [ -n "$string" ]    # Check whether it is backspace and string is not empty
    then
        printf %b "\b \b"         # '\b' moves the cursor 1 unit left and then printing '\b' then again moves the cursor left so that it looks like a character erased :)
        string=${string::-1}     # Now remove the last character from the string
        continue
    fi

    # Now check for each delimiter you want.
    case $k in
    [Ee])
        break   
        ;;  
    esac

    # Now Concatenate that byte with the previous input string
    string+=$k
    printf '%s' "$k"  # Now print the current inputted char
done
IFS="$store_IFS"        # Restoring IFS value
printf '\n%s\n' "Your string -> $string"

我不知道是否有用于执行此操作的内置命令,但您可以使用上面的 bash 代码轻松实现它。

编辑

按照评论中的建议修复了代码中的错误


推荐阅读