检查参数 $1 是否为三字符全大写字符串

Ten*_*nko 0 bash

如何检查插入的参数$1是否是3个大写字符的字符串?例如ABG。另一个例子:GTD

谢谢

Cha*_*ffy 6

使用仅限 bash 的正则表达式语法:

#!/usr/bin/env bash
if [[ $1 =~ ^[[:upper:]]{3}$ ]]; then
  echo "The first argument is three upper-case characters"
else
  echo "The first argument is _not_ three upper-case characters
fi
Run Code Online (Sandbox Code Playgroud)

...或者,为了与所有 POSIX shell 兼容,可以使用以下case语句:

#!/bin/sh
case $1 in
  [[:upper:]][[:upper:]][[:upper:]])
    echo "The first argument is three upper-case characters";;
  *)
    echo "The first argument is _not_ three upper-case characters";;
esac
Run Code Online (Sandbox Code Playgroud)