Issue
I have a test.cfg file whose contents are:
product_identifier=XR656_HD;G6_656
program_family=STR
and a script file as
#!/bin/bash
CONFIG_FILE="test.cfg"
getValueforKeyInProdConfig ()
{
key=$1
if [ -e $CONFIG_FILE ]; then
value=`cat $CONFIG_FILE | grep $key | cut -d "=" -f2 | tr -d '\r'`
echo "$value"
else
echo ""
fi
}
product_identifier="$(getValueforKeyInProdConfig "product_identifier")"
program_family="$(getValueforKeyInProdConfig "program_family")"
echo "product_identifier=$product_identifier"
echo "program_family=$program_family"
if [[ ( $program_family == "STR" ) && ( ($product_identifier == *"G6_656"*) || ($product_identifier == *"G6_646"*) ) ]]; then
echo "found string"
else
echo "unknown"
fi
But the output is:
product_identifier=XR656_HD;G6_656
program_family=STR
unknown
I am expecting the output to be
found string
How should I compare substring in bash to make the script working
Solution
Why don't you just source your CONFIG_FILE?
$ cat test.cfg
product_identifier='XR656_HD;G6_656'
program_family=STR
Script
#!/bin/bash
CONFIG_FILE="test.cfg"
. "$CONFIG_FILE"
echo product_identifier=$product_identifier
echo program_family=$program_family
[[ $program_family == "STR" ]] && \
[[ $product_identifier =~ .*G6_6[45]6 ]] && \
echo "found string" || echo "unknown"
Testing
$ ./test
product_identifier=XR656_HD;G6_646
program_family=STR
found string
$ ./test
product_identifier=XR656_HD;G6_656
program_family=STR
found string
$ ./test
product_identifier=XR656_HD;G6_676
program_family=STR
unknown
$ ./test
product_identifier=XR656_HD;G6_656
program_family=fail
unknown
Answered By - Ivan