Bash - 如何检测变量是否超过一定数量的字符

Ser*_*mer 0 bash

#/bin/bash
echo "This message may not be more than 8 characters"
read detect
Run Code Online (Sandbox Code Playgroud)

如何检测字母的数量?它会是一个 IF 语句吗?

if #detect var
then
else
fi
Run Code Online (Sandbox Code Playgroud)

编辑:如何让它重复直到用户输入正确的消息?

Win*_*nix 6

您可以像这样使用if-then-else-fi

if [[ ${#detect} -gt 8 ]] ; then
    echo "Error message..."
    exit 1
else
    echo "Good to go..."
    exit 0
fi
Run Code Online (Sandbox Code Playgroud)

exit 1一般意味着失败,exit 0一般意味着成功。无论哪种情况,您的脚本都会在exit遇到时立即结束,因此请适当使用它们。

您还可以使用隐含的if-then,这是 shell 语言中相当独特的:

[[ ${#detect} -gt 8 ]] && { echo "Error message..." ; exit 1 ; }

# successful code here
exit 0
Run Code Online (Sandbox Code Playgroud)

如果您不需要错误消息,{ ... }则单个命令不需要大括号,例如:

[[ ${#detect} -gt 8 ]] && exit 1
Run Code Online (Sandbox Code Playgroud)

可用于说“如果名为 detect 的变量 > 8,则退出”。


加强流程

通常,允许用户只有一次输入字符串的机会被认为是不礼貌的。礼貌的方法是在告诉他们字符串不超过 8 个字符后再次询问字符串。例如:

echo "Enter character string 1 to 8 characters long or press <CTRL>+C to exit."
while True ; do
    read StringVar
    [[ ${#StringVar} -ge 1 ]] && [[ ${#StringVar} -le 8 ]] && break
    echo "Sorry that string is ${#StringVar} long. Please try again."
done

# successful code here

Run Code Online (Sandbox Code Playgroud)

在这种情况下,程序不断请求输入,直到StringVar获得变量并且它大于或等于 1 并且小于或等于 8,此时while使用break命令打破外观。

或者,用户可以按Ctrl+C/kbd> 终止 bash 脚本。

简洁的线条:

[[ ${#StringVar} -ge 1 ]] && [[ ${#StringVar} -le 8 ]] && break
echo "Sorry that string is ${#StringVar} long. Please try again."
Run Code Online (Sandbox Code Playgroud)

...可以像这样变得冗长可笑:

if [[ ${#StringVar} -ge 1 ]] ; then
    if [[ ${#StringVar} -le 8 ]] ; then
        break
    else
        echo "Sorry that string is ${#StringVar} long. Please try again."
        continue
    fi
else
    echo "Sorry that string is ${#StringVar} long. Please try again."
    continue
fi
Run Code Online (Sandbox Code Playgroud)

虽然没有错,但它浪费了程序员和系统的时间。