0

I tried the following but without success

[root@OBAMA~]# bash
[root@OBAMA~]# a=HelloWorld

[root@OBAMA~]# [[ $a == [A-Za-z] ]] && echo "YES ITS STRING"

( the command not prints anything )

[root@OBAMA~]# [[ $a == [A-Z][a-z] ]] && echo "YES ITS STRING"

( the command not prints anything )

2 Answers 2

1

Change your command lke below.

$ [[ $a =~ [A-Za-z]+ ]] && echo "YES ITS STRING"
YES ITS STRING
  • Use =~ operator to test an input string against a regex.

  • Add + next to the character class, so that it would repeat the previous pattern or token one or more times. Here it's unnecessary.

Add anchors , in-order to do an exact string match. [[ $a =~ [A-Za-z] ]] && echo "YES ITS STRING" alone will print the string YES ITS STRING because the variable a contains atleast an alphabet.

$ a="HelloWorld"
$ [[ $a =~ ^[A-Za-z]+$ ]] && echo "YES ITS STRING"
YES ITS STRING
$ a="Hello World"
$ [[ $a =~ ^[A-Za-z]+$ ]] && echo "YES ITS STRING"
$ 
Sign up to request clarification or add additional context in comments.

Comments

1

how do you define "a string"

[[ -n $a ]] && echo variable a is not empty

[[ $a == *[[:alpha:]]* ]] && echo variable a contains a letter

shopt -s extglob failglob
[[ $a == +([[:alpha:]]) ]] && echo variable a only has letters

Your glob expressions are not matching because your checking that your variable contains only 1 character or 2 characters.

2 Comments

how do you define "a string" --> string must include only chars ( A-Z /a-z )
choose between Avinash's anchored regular expression or my extended glob, both will satisfy that requirement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.