简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM