gumik
gumik

Reputation: 623

echo asterix at the end of variable in bash

I have the following script.

#!/bin/bash

PHOTOS_DIR=$1
PHOTOS_LIST=$2

while read line           
do
    echo "line: ${line}"
    pattern="*`echo \"$line\" | tr ' ' '*'`*"
    echo "pattern: ${pattern}"
done <$PHOTOS_LIST

It gives very weird output. For example:

line: 20121224-100 5777
*attern: *20121224-100*5777
line: 20121224-100 5778
*attern: *20121224-100*5778

I tried with escaping last asterix character but it does not work as well.

line: 20121224-100 5777
\*ttern: *20121224-100*5777
line: 20121224-100 5778
\*ttern: *20121224-100*5778

If I try similar thing in bash console it works well:

$ line='a b'
$ pattern="*`echo \"$line\" | tr ' ' '*'`*"
$ echo "pattern: ${pattern}"
pattern: *a*b*

What is wrong in the script?


I did another test. The following works well.

for line in "20121224-100 5777" "20121224-100 5778"
do
    echo -e "line: ${line}"
    pattern="*`echo \"$line\" | tr ' ' '*'`*"
    echo -e "pattern: ${pattern}"
done

There is something with this while read line loop. But what?

Upvotes: 0

Views: 114

Answers (1)

anishsane
anishsane

Reputation: 20980

Your input file $PHOTOS_LIST has CRLF line endings.
Run dos2unix $PHOTOS_LIST to change the file for good.

Alternately, try this:

#!/bin/bash

PHOTOS_DIR=$1
PHOTOS_LIST=$2

while read line           
do
    echo "line: ${line}"
    pattern="*`echo \"$line\" | tr ' ' '*'`*"
    echo "pattern: ${pattern}"
done < <(tr -d '\n' < $PHOTOS_LIST)

Upvotes: 4

Related Questions