0

I want to check if an input on my shell script was an alphabetic character or a character. how can I achieve that?

5
  • What do you mean by character? Almost every argument in bash is a character
    – Ikaros
    Dec 12, 2016 at 17:06
  • I mean alphabetic characters
    – Luis Veliz
    Dec 12, 2016 at 17:09
  • it's personal preference, but when I want to validate a string I personally use egrep to run regexp against it and check the return code.
    – Bratchley
    Dec 12, 2016 at 17:11
  • example: echo $string | egrep '^[0-9]+$'
    – Bratchley
    Dec 12, 2016 at 17:12
  • You can also use awk for this and there's probably some fancy bash syntax out there for it though.
    – Bratchley
    Dec 12, 2016 at 17:13

4 Answers 4

2

Your question is really vague, so some guesswork here:

#!/bin/bash
input=$1
if [[ -z "$input" || $input == *[^[:digit:]]* ]]; then
    echo "your input '$input' is not a number" >&2
    exit 1
fi
echo "congrats, '$input' is a number"

In bash, inside [[...]] the == operator is a pattern matching operator, so we're looking for any non-digit characters there.

2
  • your code snippet is clearer to me (once I read it properly) but it looks like it doesn't check for an empty string.
    – Bratchley
    Dec 12, 2016 at 17:18
  • Right, it didn't. updated Dec 12, 2016 at 17:19
1

If your input is in $VAR....

if [ -z "${VAR//[0-9]/}" -a ! -z "$VAR" ]; then
  echo only has digits
fi 
1

Checking for an alphabetical character is just a matter of:

case $input in
  ([[:alpha:]]) echo one alpha character;;
  (*) echo 'non-alpha or not one character (or non-character)';;
esac

The character is decoded as per the locale's character set/encoding, and the locale is queried again to check if it's in the alphabetical character class.

Checking for $input being a character is trickier.

case $input in
  (?) echo one character
esac

Is meant to check for that. However, with most shells, that will also return true if $input contains one byte that doesn't form a valid character. To account for that you could do:

case $input in
  ([[:alpha:]]) echo one alpha character;;
  (?)
     n_chars=$(($(printf %s "$input" | wc -m)))
     if [ "$n_char" -eq 1 ]; then
       echo one character
     else
       echo one byte that is not a character
     fi;;
  ("") echo empty;;
  (*) echo anything else
esac
0

While the others answers are great, here is a one-liner solution

grep -q '^[[:alnum:]]*$' <<< "$mybar" && success_command || failure_command

If you want to return do failure command on empty string, use the following

grep -q '^[[:alnum:]]\+$' <<< "$mybar" && echo "success" || echo "failure"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .