1

I'm testing out some bash code and getting errors as I'm reading the final row of file and comparing it to another:

#!/bin/bash
NEW_EVENT_TAIL=`echo tail -1 new_events.txt`
EXISTING_EVENT_TAIL=`echo tail -1 new_events.txt`

if ["$NEW_EVENT_TAIL"="$EXISTING_EVENT_TAIL"];
then
    echo "in list"
else
    echo "not in list"
fi

Based on this code, and using the exact same file, I would expect the "in list" to be printed. Instead, the "not in list" is printed. The message I get:

-bash: [tail -1 new_events.txt=tail -1 new_events.txt]: command not found
codeforester
  • 39,467
  • 16
  • 112
  • 140
jKraut
  • 2,325
  • 6
  • 35
  • 48
  • 1
    The first problem is that you're lacking an IFS character (by default any whitespace character) between `[` and what follows, as well as between `]` and what precedes. This leads `bash` to parse the whole condition as a single command, which it of course fails to find. – Aaron Oct 03 '17 at 15:57
  • BTW -- variables you define yourself (as opposed to ones with meaning to the operating system or shell) should have at least one lower-case character. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, fourth paragraph: *The name space of environment variable names containing lowercase letters is reserved for applications. Applications can define any environment variables with names from this name space without modifying the behavior of the standard utilities.* – Charles Duffy Oct 03 '17 at 16:03

1 Answers1

2

Just remove 'echo':

tail -1 new_events.txt

and change the if with the following:

if [ "$NEW_EVENT_TAIL" = "$EXISTING_EVENT_TAIL" ];

The overall script

NEW_EVENT_TAIL=`tail -1 new_events.txt`
EXISTING_EVENT_TAIL=`tail -1 new_events.txt`

if [ "$NEW_EVENT_TAIL" = "$EXISTING_EVENT_TAIL" ];
then
    echo "in list"
else
    echo "not in list"
fi
farbiondriven
  • 2,450
  • 2
  • 15
  • 31
  • if [ $NEW_EVENT_TAIL = $EXISTING_EVENT_TAIL ]; – farbiondriven Oct 03 '17 at 16:01
  • 1
    (Also, see the "Answer Well-Asked Questions" section in [How to Answer](https://stackoverflow.com/help/how-to-answer)). – Charles Duffy Oct 03 '17 at 16:06
  • my bad, I didn't put the whole script. I edited the reply – farbiondriven Oct 03 '17 at 16:08
  • 1
    Much improved. I would suggest avoiding all-caps variable names -- as suggested in [the relevant POSIX standard](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html) and using `$()` in place of backticks (being equally POSIX-compliant, but easier to nest and with fewer side effects on other syntax), but now nothing in this reply is outright incorrect. – Charles Duffy Oct 03 '17 at 16:10