How do you compare chains in Bash?

5

I'm using Bash in Linux and I found an example in which I compared the strings in this way but apparently it does not work.

In this case, $a is what the user writes to the console.

#!/bin/bash
a=$1
if [ "${a}"=="static" ]; then
(instrucciones)
else
(instrucciones)
fi
    
asked by FrEqDe 17.02.2017 в 06:13
source

3 answers

5

You can do help test for more information:

Empty string:

if [ -z "$VAR" ]; then ...

Equal chains

if [ "$VAR" = "CADENA" ]; then ...

Different chains

if [ "$VAR" != "CADENA" ]; then ...
    
answered by 17.02.2017 / 06:25
source
5

In Bash you can compare the strings using the syntax:

[[ $variable == "valor" ]]

Note that here $variable do not need to have double quotes.

Here, both [[ and == are characteristic of Bash (what we call Bashisms ). The standard (that is, what POSIX defines) is to use [ and = :

[ "$variable" = "valor" ]

In which case the variable must be enclosed in quotation marks to protect us from word splitting .

Note that the syntax is of the form:

if [ condiciones ]
# ^ ^           ^

That is, the spaces around [ are necessary, because [ is a command itself. This command is called test and therefore you can use [ and test indistinctly, as well as search your instructions doing man test (as indicated by Trauma in your answer):

$ v="hola"
$ if test "$v" = "hola"; then echo "si"; fi
si
$ if [ "$v" = "hola" ]; then echo "si"; fi
si

Additional explanation regarding the use of double quotes within [ and [[ .

When we use [ , the variables expand causing errors if we do not put double quotes:

$ v="hola que tal"

With [ and quotation marks, the expansion is correct:

$ if [ "$v" = "hola que tal" ]; then echo "si"; fi
si

If we remove the quotes, it gives an error:

$ if [ $v = "hola que tal" ]; then echo "si"; fi
bash: [: too many arguments

Well, it's expanding to:

$ if [ hola que tal = "hola que tal" ]; then echo "si"; fi

giving 5 arguments to test instead of the maximum 3 accepted.

On the other hand, with the Bashismo [[ you can omit the quotes:

$ if [[ $v = "hola que tal" ]]; then echo "si"; fi
si
    
answered by 17.02.2017 в 08:09
1

Examples:

test="test"
if [[ $test == "test" ]]; then
    echo "Son iguales las cadenas."
elif [[ ! $test ]]; then
    echo "La cadena está vacía entonces."
elif [[ $test =~ "^t" ]]; then
    echo "El regex indica que la cadena ${test} empieza con t"
elif [[ ${test:1:1} == "e" ]]; then
    echo "Aquí estamos comparando el caracter 1 con la letra e, es verdadero"
fi

everyone indicates what they do, it's easy to understand.

    
answered by 20.03.2017 в 07:51