0

I have a test.txt file that looks like this:

flask=1.0.1
control=1.0.1
device=1.0.1

Now, I want to create an if statement that if flask=1.0.1, do something and if flash=1.0.1_hotfix do something else.

I tried with grep -iFq but no luck, I am newbie to bash and also to programming.

Can anyone show me a doc that explains how to do so? It's really simple task.

Thank you all!

0

4 Answers 4

4

With bash and if:

source test.txt

if [[ $flask == 1.0.1 ]]; then
  echo "do something"
fi

if [[ $flask == 1.0.1_hotfix ]]; then
  echo "do something else"
fi

Or with bash and case:

source test.txt

case $flask in
1.0.1)
  echo "do something"
  ;;
1.0.1_hotfix)
  echo "do something else"
  ;;
esac

Or in a denser presentation:

source test.txt

case $flask in
         1.0.1) echo "do something" ;;
  1.0.1_hotfix) echo "do something else" ;;
esac
Sign up to request clarification or add additional context in comments.

1 Comment

Note to the unwary (or the newbie): this will execute any commands in test.txt. For this to work, test.txt must be valid shell code and not contain any commands with undesirable side effects.
1

Grep is fine, just notice that flask=1.0.1 is a substring of flask=1.0.1_hotfix, so you need to do full string comparison or check for the string end.

flask=$( grep ^flask= test.txt )
if [ "$flask" == flask=1.0.1 ] ; then
    ...
elif [ "$flask" == flask=1.0.1_hotfix ] ; then
    ....
fi

Comments

0

I've understood you correctly?

[root@212-24-57-104 Build]# cat 1
flask=1.0.1
control=1.0.1
device=1.0.1
[root@212-24-57-104 Build]# cat ez.sh
#!/bin/bash
a=( $(cat 1) )
for ver in "${a[@]}"
do 
    if [ $(echo "${ver}" | awk -F= '{print $NF}') == "1.0.1" ]
    then 
        echo "Do something virh $ver"
    else 
        echo "Do anything else with $ver"
    fi
done

1 Comment

Populating the a array like this is risky, due to word splitting and filename expansion. This is safer: mapfile -t a < filename
0

A couple of other options:

  1. use grep to get the value

    flask_value=$( grep -oP '^flask=\K.*' test.txt )
    case $flask_value in 
        1.0.1) ... ;;
        # etc
    esac
    
  2. iterate over the file with just bash:

    while IFS="=" read var value; do
        if [[ $var == "flask" ]]; then
            case $value in 
                1.0.1) ... ;;
                # etc
            esac
        fi
    done < test.txt
    

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.