bashecho

echo output of logical expression in bash script ubuntu


var1 = 'abc'
var2 = 'bc'

echo "Print result: $[[$var1 =~ $var2]]"

This echo command is not working. How would I print the output of the logical expression $var1 =~ $var2 correctly?

I want to check if var2 is a substring of var1. So the expected output would be "Print result: 1".


Solution

  • # Test whether var2 is a substring of var1
    [[ $var1 == *$var2* ]]
    # $? here is 0 if the condition is true and 1 if it is false.
    # Set `result` to 1 if it is, and to 0 if it isn't
    ((result = 1 - $?))
    

    This solves the problem as specified by the OP. However, I want to point out that this way of modelling true/false is rather unusual. In most cases, true would be modelled by 0 and false by 1.

    Of course you don't need to use a variable, if you just want to echo:

    [[ $var1 == *$var2* ]]
    echo $((1 - $?))
    

    Or you do it like this:

    ! [[ $var1 == *$var2* ]]
    echo $?