$a ...">

Bash: string contains hyphen

I am trying to check if string string1 contains another string2. I do it as follows:

a=$(tempfile) echo "eafg" > $a if [[ $a == *e* ]] then echo "contains" fi 

Now I'm trying to see if the string contains a hyphen:

 a=$(tempfile) echo "22:00:00-02:00" > $a if [ $a == *-* ] then echo "contains" fi 

This does not work. I also tried:

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

Without success ...

Thank you in advance

+6
source share
2 answers

The following code snippet causes problems

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

Here you write the file $a , and then try to do a string comparison.


Try to execute

 a="22:00:00-02:00" if [[ $a == *-* ]] then echo "contains" fi 
+5
source

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

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

Say:

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

Following

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

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

+1
source

Source: https://habr.com/ru/post/958634/


All Articles