1

I have a text file called VERSION.txt with only one line of content:

2.0.5

I'd like to use a shell script to read that version number and assign it to a env variable like so:

export APP_VERSION='2.0.5'

This is about as close as I could come.

input="VERSION.txt"
while IFS= read -r line
do
    export APP_VERSION=$line

echo 'App version is' ${APP_VERSION}
done < "$input"

Which seems to work, but when I echo $APP_VERSION I get a blank result.

Any tips?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Don T Spamme
  • 199
  • 7
  • This code should certainly leave the last line in your file in the `APP_VERSION` variable. That said, where are you doing the `echo` to check if the variable was populated? Remember, exporting a variable only applies to that process and its children; it doesn't apply to the parent process (which is to say, the program that _started_ your script). – Charles Duffy Oct 03 '21 at 16:25
  • Also, note that you it would be more correct as `echo "App version is ${APP_VERSION}"` -- you want the parameter expansion to be inside double quotes, not in an unquoted context. Otherwise if `APP_VERSION='*'`, the `echo` would write a list of filenames in the current directory instead of that `*`. See also [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Oct 03 '21 at 16:27

1 Answers1

3
input="VERSION.txt"
export APP_VERSION=$(cat "$input")
echo "App version is ${APP_VERSION}"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    The OP only wants one line to be read, not the whole file, as I read the question. Maybe replace `cat` with `head -n 1`, or just the whole thing with a not-in-a-loop `read -r APP_VERSION <"$input" && export APP_VERSION`? – Charles Duffy Oct 03 '21 at 16:25
  • 1
    @CharlesDuffy I read the question as saying the file only has one line, which means reading line-by-line is unnecessary. Perhaps the OP didn't consider just reading the whole file in. – John Kugelman Oct 03 '21 at 16:26
  • Possibly. That said, insofar as the OP is describing their problem as the variable not being set after their loop finishes (and they aren't reporting any `App version is` output as would be expected with a blank line at the end overwriting the non-blank value from the first line), I suspect that the real problem is something completely different that this doesn't even attempt to address -- f/e, expecting the `export` to make the shell that started the script able to see the variable the script sets. – Charles Duffy Oct 03 '21 at 16:29
  • Thank you Cyrus, that did the trick. I hadn't even considered just reading the whole file out because you were correct there is only the one line. Thanks a bunch. – Don T Spamme Oct 03 '21 at 17:45
  • @Cyrus : The OP is using bash. Perhaps `export APP_VERSION=$(<$input)` would be more idiomatic for bash. – user1934428 Oct 04 '21 at 10:05