1

Thanks for looking into my concern.

I have a text file with key value pairs. like version.txt and content is Version=1.0.0.AA

Now I want to read this text file use this version number inside my scripts.

I am handling this in windows using below script:

For /F "tokens=1* delims==" %%A IN (..\version.txt) DO (
    IF /I "%%A"=="version" set APP_VERSION=%%B
)
echo Application Version is "%APP_VERSION%"

Could you please help me to achieve the same in Shell scripts.

Thanks.

Ras
  • 543
  • 1
  • 9
  • 25

1 Answers1

6

You can just do

source version.txt
echo ${Version}

For version.txt

Version=1.0.0SomeVersion

source [file] sources the content of [file] into the script

Version=1.0.0ABC happens to be a valid variable declaration in bash

(Hint: there are no spaces between the equal sign, the variable name and the value)

(Hint: Variables in bash are case sensitive)

Because of that you can just source your key-value file and use the contents as variables.

If you want to check if the variable is unset or empty you can use

if [ -z "$Version" ]; then
    echo "Version is unset or empty!"
    exit 1
fi
  • I have tried this already. I see some strange issue. ../version.txt: line 1: $'\r': command not found – Ras Jul 20 '17 at 21:43
  • That's because the line ending of the file you are using is windows. Do a `dos2unix version.txt` to convert your file to linux file endig. – Lukas Isselbächer Jul 20 '17 at 21:45
  • Thank you so much. You are right, it has EOL char's. – Ras Jul 20 '17 at 21:46
  • Note: `source` is not POSIX so you may have portability issues to other shells. The equivalent `'.'` operator is. Simply `. version.txt` is guaranteed to work. – David C. Rankin Jul 20 '17 at 22:05