shell: strange string concatenation behavior

1.4k views Asked by At

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.

2

There are 2 answers

1
SLePort On BEST ANSWER

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)
1
ClaudioM On

I've tried your script and it works fine for me:

./testConcat
line pdb8mhtA
pdbfile pdb8mhtA.pdb

btw you could try to "preserve" the "."

while read line
do
  echo line ${line}
  pdbfile=${line}\.pdb
  echo pdbfile ${pdbfile}
done < myfile

as you can see the result is the same

./testConcat
line pdb8mhtA
pdbfile pdb8mhtA.pdb