tags:

views:

120

answers:

2

Case in point. I want to know if some set of files have as a first line '------'.

So,

for file in *.txt
do
    if [[ `head -1 "$file"` == "------" ]]
    then
        echo "$file starts with dashes"
    fi
done

Thing is, head returns the content with a newline, but "------" does not have a newline.

Why does it work?

+4  A: 

The backticks strip the trailing newline. For example:

foo=`echo bar`
echo "<$foo>"

prints

<bar>

even though that first echo printed out "bar" followed by a newline.

Laurence Gonsalves
Well, this too! :-)
Vinko Vrsalovic
In fact, it's only this. My question is wrong :(
Vinko Vrsalovic
Relevant BASH Manual quote: "Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted."
Vinko Vrsalovic
I thought it was a trick question. :-)
Laurence Gonsalves
A: 

Bash performs word splitting on the result of command substitution i.e. head -1 "$file"

Word splitting will remove newlines among other things.

nos