Home > Software design >  Check if a parameter $1 is a three-character all-caps string
Check if a parameter $1 is a three-character all-caps string

Time:11-22

How can I check if the parameter inserted $1 is a string of 3 chars in uppercase? For example ABG. another example: GTD

Thanks

CodePudding user response:

Using bash-only regular expression syntax:

#!/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

...or, for compatibility with all POSIX shells, one can use a case statement:

#!/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

CodePudding user response:

I would use:

LC_ALL=C

[[ "$1" == [A-Z][A-Z][A-Z] ]] || exit 1

Or

LC_ALL=C

if [[ "$1" != [A-Z][A-Z][A-Z] ]]; then
    echo "$1: invalid input" >&2
    exit 1
fi

As per Charles' comment, A-Z is a character range, which is not equivalent to "all upper case latin letters" in all locales, so we can set the locale with LC_ALL=C.

You can use [[:upper:]] instead of [A-Z] if you don't want to set LC_ALL=C.

Alternatively, there's shopt -s globasciiranges, but it only works in bash version 4.3 or later (and is set by default in version 5.0 and later).

Note also, that using glob patterns in a string comparison is bash specific, and won't work in sh.

  •  Tags:  
  • bash
  • Related