Bash string comparison


#!/bin/bash

function test(){
echo ""
echo "TEST $1"
echo "VAR_1: $VAR_1 VAR_2: $VAR_2 "
if [ "$VAR_1" = "false" ]; then echo " VAR_1 is false"; fi
if [ "$VAR_2" = "false" ]; then echo " VAR_2 is false"; fi
if [ "$VAR_1" = "false" ] || [ "$VAR_2" = "false" ]; then echo " At least one is false"; fi
}
VAR_1='true';
VAR_2='true';
test 1

VAR_1='true';
VAR_2='false';
test 2

VAR_1='false';
VAR_2='false';
test 3

function test2(){
echo ""
echo "TEST $1"
echo "VAR_3: $VAR_3 VAR_4: $VAR_4 "
[ -n "$VAR_3" ] && echo " VAR_3 is not null"
[ -z "$VAR_3" ] && echo " VAR_3 is null"
[ -n "$VAR_4" ] && echo " VAR_4 is not null"
[ -z "$VAR_4" ] && echo " VAR_4 is null"
}

VAR_3=""
VAR_4=""
test2 4

VAR_3="3"
VAR_4=""
test2 5

Result

$ /c/tmp/bashtest.sh

TEST 1
VAR_1: true VAR_2: true

TEST 2
VAR_1: true VAR_2: false
VAR_2 is false
At least one is false

TEST 3
VAR_1: false VAR_2: false
VAR_1 is false
VAR_2 is false
At least one is false

TEST 4
VAR_3: VAR_4:
VAR_3 is null
VAR_4 is null

TEST 5
VAR_3: 3 VAR_4:
VAR_3 is not null
VAR_4 is null

Leave a Reply

Your email address will not be published. Required fields are marked *


3 × four =