I'm trying to extract a version string from a text file with contains the major, minor and patch elements of the specific version.
This file is named versioninfo.txt
and its contents are like the following:
MAJOR 2
MINOR 0
PATCH 0
I'm writing a bash script to extract the values from that file and generate a string like v2.0.0
but I'm struggling when building the complete version string.
This is the bash script I wrote
#!/bin/bash
function extractVersionElement() {
line=$(sed "${1}q;d" versioninfo.txt)
version="${line#* }"
echo "${version}"
}
function extractVersion() {
major="$(extractVersionElement 1)"
minor="$(extractVersionElement 2)"
patch="$(extractVersionElement 3)"
echo "major: ${major}"
echo "minor: ${minor}"
echo "patch: ${patch}"
}
version="$(extractVersion)"
echo "$version"
Which outputs, correctly reading the single version elements:
$ ./extract_version.sh
major: 2
minor: 0
patch: 0
Changing the script to:
#!/bin/bash
function extractVersionElement() {
line=$(sed "${1}q;d" versioninfo.txt)
version="${line#* }"
echo "${version}"
}
function extractVersion() {
major="$(extractVersionElement 1)"
minor="$(extractVersionElement 2)"
patch="$(extractVersionElement 3)"
# Here I try to create the complete version string
echo "v${major}.${minor}.${patch}"
}
version="$(extractVersion)"
echo "$version"
Outputs the following, truncating the output:
$ ./extract_version.sh
.0
Any idea on how to solve this?
Working script
The problems were caused by \r
at the end of each line. This is the working script which solves the problem:
#!/bin/bash
function extractVersionElement() {
# read the nth line of the versioninfo file
line=$(sed "${1}q;d" versioninfo.txt)
# remove \r and \n from the string which were causing
# problems when creating the final version string
line=${line//[$'\t\r\n']}
# extract the version after the space
version="${line#* }"
# return the read version
echo "${version}"
}
function extractVersion() {
major="$(extractVersionElement 1)"
minor="$(extractVersionElement 2)"
patch="$(extractVersionElement 3)"
# combine the three version elements into one version string
echo "v${major}.${minor}.${patch}"
}
version="$(extractVersion)"
echo "$version"