2

I am trying to do a one time check about apache's mod-status page for updates like this(this is just a test script):

firstcontent=$(lynx -dump http://some-server/server-status-page)
echo $firstcontent > /tmp/myfirstcontentfiles.txt
nextcontent=$(lynx -dump http://some-server/server-status-page)
prevcontent=`cat /tmp/myfirstcontentfiles.txt`
#this always returns false, but their contents are same
if [ "$prevcontent" == "$firstcontent" ]; then   echo "match"; fi
#but this returns true 
if [ "$nextcontent" == "$firstcontent" ]; then   echo "match"; fi

My question is why $prevcontent and $firstcontent comparision returns false whilst I am supposed to get a true return value? is anything happening behind the scene when I am saving it in a file?

  • 4
    You'll lose distinctive whitespace characters when you do echo $firstcontent > /tmp/myfirstcontentfiles.txt. They'll get replaced by blanks. Try echo "$firstcontent" > /tmp/myfirstcontentfiles.txt instead. – Mark Plotnick Dec 24 '14 at 21:13
  • 3
    Double quoting $firstcontent on the second line should fix your bug as @Mark says. I don't recommend storing the downloaded data in shell variables though. Instead, try downloading directly to a file and using the cmp command to compare. Also consider using wget or curl for better portability. – Graeme Dec 24 '14 at 22:34
  • I would use diff for comparing the two files. – steviethecat Dec 24 '14 at 22:44

1 Answers1

4

Read Why does my shell script choke on whitespace or other special characters? to understand the why. The 1-sentence version is: always use double quotes around variable substitutions.

echo "$firstcontent" >/tmp/myfirstcontentfiles.txt

mostly works: it doesn't collapse whitespace or expand wildcards in the value of the variable. However this still removes trailing empty lines (command substitution does that) and, in some shells, the echo command expands backslashes. In your script, the easiest way to write the pristine output of the command to a file is to do it before it reaches the shell:

firstcontent=$(lynx -dump http://some-server/server-status-page | tee /tmp/myfirstcontentfiles.txt)