RMNexus
RMNexus

Reputation: 1

BASH - Get number from a file and use it

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!

Upvotes: 0

Views: 124

Answers (4)

glenn jackman
glenn jackman

Reputation: 246754

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
    

Upvotes: 0

Cyrus
Cyrus

Reputation: 88563

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

Upvotes: 4

sahaquiel
sahaquiel

Reputation: 1838

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

Upvotes: 0

choroba
choroba

Reputation: 241768

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

Upvotes: 1

Related Questions