Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: String contains hyphen

I am trying to see if string1 contains another string2. I do this in this manner:

a=$(tempfile)
echo "eafg" > $a

if [[ $a == *e* ]]
then
   echo "contains"
fi

Now I try to see if a string contains a hyphen:

a=$(tempfile)    
echo "22:00:00-02:00" > $a

if [ $a == *-* ]
then
   echo "contains"
fi

It doesn't work. I also tried:

if [ $a == *--* ]
if [ $a == *---* ]
if [[ $a == *-* ]]
if [[ $a == *--* ]]
if [[ $a == *---* ]]

With no success...

Thanks in advance

like image 896
user1064285 Avatar asked Nov 22 '13 10:11

user1064285


2 Answers

Following piece of code brings problems

a=$(tempfile)    
echo "22:00:00-02:00" > $a

Here you are writing to a file $a and then try to do string comparison.


Try following

a="22:00:00-02:00"

if [[ $a == *-* ]]
then
   echo "contains"
fi
like image 168
jkshah Avatar answered Sep 23 '22 02:09

jkshah


You redirected the string to a file, so read it from the file while comparing.

The variable a contains the name of the file and not the contents.

Say:

if [ $(<$a) == *-* ];
then
   echo "contains"
fi

The following

if [[ $a == *e* ]];
then
   echo "contains"
fi

worked for you because the variable holding the name of the file contained the letter e.

like image 23
devnull Avatar answered Sep 21 '22 02:09

devnull