Search code examples
bashshellstring-concatenation

shell: strange string concatenation behavior


I write a scipt like this:

#!/bin/bash
while read line
do
  echo line ${line}
  pdbfile=${line}.pdb  
  echo pdbfile ${pdbfile}
done < myfile

The result is:

line pdb8mhtA
.pdbfile pdb8mhtA

While it is supposed to be

line pdb8mhtA
pdbfile pdb8mhtA.pdb

What's wrong with this? Why the string concatenation does not work? And why the strange dot at the beginning of the line?
I replace with pdbfile=${line}'.pdb'. That does not change the result.


Solution

  • The "string goes to the beginning of the line" is symptomatic of a carriage return in your $line that you can among many other ways remove with a tr pipe to your file:

    while IFS= read -r line
    do
      echo "line ${line}"
      pdbfile=${line}.pdb  
      echo "pdbfile ${pdbfile}"
    done < <(tr -d '\r' <file)