0

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

3
  • I ran the program as-is and it worked for me (on Mac). I got: product_identifier=XR656_HD;G6_656 program_family=STR found string Can you please try it on another machine? Commented May 20, 2021 at 4:39
  • 1
    value=$(grep $key); value="${value##*=}"; (Parameter Expansion with substring removal) Commented May 20, 2021 at 4:49
  • issue was with whitespace, was not working since there was whitespace after the first line in the cfg file Commented May 20, 2021 at 7:02

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.