2power10 2power10 - 1 year ago 73
Bash Question

Weird behavior when concatenate string in bash shell

I have a file store version information and I wrote a shell to read two fields and combine them. But when I concatenate those two fields, it show me a werid result.

version file:

buildVer = 3
version = 1.0.0

script looks like:


sdk_ver=`cat $verFile | sed -nE 's/version = (.*)/\1/p'`
build_ver=`cat $verFile | sed -nE 's/buildVer = (.*)/\1/p'`
echo $sdk_ver
echo $build_ver
echo $tagname

The output shows


I tried to echo the sdk_ver directly without read it from file, this piece of script works well. So I think it may relate to the sed, but I couldn't figure out how to fix it.

Does anyone know why it acts like that?

Answer Source

You're getting this problem because of presence of DOS line ending i.e. \r in each line of version file.

Use dos2unix or this sed command to remove \r first:

sed -i 's/\r//' version

btw you can also simplify your script using pure BASH constructs like this:


while IFS='= ' read -r k v; do
   declare $k="$v"
done < <(sed $'s/\r//' version)

echo "$tagname"

This will give output:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download