Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an argument has a single character in shell

I'm trying to make a script to check if an argument has a single uppercase or lowecase letter, or if its anything else (a digit or a word for example.)

So far got this done:

if echo $1 | egrep -q '[A-Z]';
    then echo "Uppercase";
elif echo $1 | egrep -q '[a-z]';
    then echo "Lowercase";
else
    echo "FAIL";
fi 

Need to make it to fail me not only if it isnt a letter, but if I insert a word or 2 letters.

like image 813
Zasito Avatar asked Nov 20 '12 23:11

Zasito


People also ask

How do you check if a file contains a specific string?

You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.

What is difference between $@ and $* in shell?

$0 Stores the first word of the entered command (the name of the shell program). $* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).

What is $@ in SH?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you check if a variable is a string in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.


1 Answers

You was very close !

if echo $1 | egrep -q '^[A-Z]$';
    then echo "Uppercase";
elif echo $1 | egrep -q '^[a-z]$';
    then echo "Lowercase";
else
    echo "FAIL";
fi
  • I've just added the special characters ^ & $, means respectively start of line & end of line
  • no need egrep there, grep is sufficient
like image 135
Gilles Quenot Avatar answered Sep 19 '22 09:09

Gilles Quenot