简体   繁体   English

Bash,如何检查变量中的控制字符(非可打印字符)?

[英]Bash, how to check for control character(non-printable character) in a variable?

I have a Bash statement to get user input(a single character) into tmpchar : 我有一个Bash语句来将用户输入(单个字符)输入tmpchar

read -n 1 -t 1 tmpchar

and I can check for printable character input like this: 我可以像这样检查可打印的字符输入:

if [ "$tmpchar" = "n" ] || [ "$tmpchar" = "N" ]; then
  # do something...
fi

Now my question is: If user input just a Return, or ESC, or Ctrl+a, Ctrl+b etc, how do I check for them? 现在我的问题是:如果用户仅输入Return或ESC或Ctrl + a,Ctrl + b等,该如何检查它们?

ENV: openSUSE 12.3 , Bash 4.2.42(1)-release ENV:openSUSE 12.3,Bash 4.2.42(1)-发行版

Maybe you're looking for ANSI-C quoting . 也许您正在寻找ANSI-C引用 Eg, Ctrl-a is represented as $'\\ca' . 例如,Ctrl-a表示为$'\\ca'

Use the regex match operator =~ inside of [[ ... ]] : [[ ... ]]内使用正则表达式匹配运算符=~

if [[ $tmpchar =~ [[:cntrl:]] ]]; then
  # It's a control character
else
  # It's not a control character
fi

Note that read -n1 won't do what you expect for a variety of special characters. 请注意,对于各种特殊字符, read -n1不会实现您所期望的。 At a minimum, you should use: 至少应使用:

IFS= read -r -n1

Even with that, you'll never see a newline character: if you type a newline, read will set the reply variable to an empty string. 即使这样,您也永远不会看到换行符:如果键入换行符,则read会将reply变量设置为空字符串。

If you want to know if a character isn't a member of the set of printable characters, use a complementary set expression. 如果您想知道某个字符是否不是可打印字符集的成员,请使用互补的集合表达式。 This seems to work fine with case : 这似乎适用于case

for c in $'\x20' $'\x19'; do
    case "$c" in
        [[:print:]]) echo printable;;
        [^[:print:]]) echo 'not printable';;
        *) echo 'more than one character?';;
    esac
done

(outputs printable and then non printable ) (输出printable ,然后non printable

for c in $'\x20' $'\x19'; do
    if [[ $c = [[:print:]] ]]; then
        echo printable
    fi
    if [[ $c = [^[:print:]] ]]; then
        echo not printable
    fi
done

works as well. 也可以。 If you want to know what characters sets your system supports, look at man 7 regex on linux or man 7 re_format on OS X. 如果您想知道哪些字符设置了系统支持,请查看linux上的man 7 regex或OS X上的man 7 re_format

You can filter the input with tr : 您可以使用tr过滤输入:

read -n 1 -t 1 tmpchar
clean=$(tr -cd '[:print:]' <<< $tmpchar)
if [ -z "$clean"]; then
    echo "No printable"
else
    echo "$clean"
fi

I find a trick to check for a sole Return input. 我发现了一种检查唯一的Return输入的技巧。

if [ "$tmpchar" = "$(echo -e '')" ]; then
  echo "You just pressed Return."
fi

In other word, the highly expected way by @ooga, 换句话说,@ ooga非常期待的方式,

if [ "$tmpchar" = $'\x0a' ]; then
  echo "You just pressed Return." # Oops!
fi

does not work for Return anyhow, hard to explain. 无论如何都不适用于Return,很难解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM