Read 2 lines from File, Run Command based off output

Okay, so I have a file containing line after line of three digit numbers. I need a script that does an action based on the last two numbers in this list.

So.... To get the last two numbers, I can have the script do

tail -2 filename.txt

But where I run into trouble is as follows. If these last two numbers, retrieved via tail, are Greater than 400, I want to run a command. The command is irrelevant, so lets just make something up: touch filename.txt

If it helps, it doesnt necessarily have to do > 400. It would still meet my needs if it did something more like. If = 400 or 401 or 402 or 403 or 404 or 405 as there will really only be that number set, with nothing over 405.

So the script can function with whatever is easier.

Thanks a ton! :o

Try:

tail -2 filename.txt | tr "\n" " " | read a b
if [ $a -gt 400 ] && [ $b -gt 400 ]; then 
  your command 
fi

Thanks for the post Bartus. When I run this, it says

./filescript.sh: line 2: [: -gt: unary operator expected

So before re-posting I tried to find the answer via Google again. No luck. But I have identified it does not seem to be getting variables for a and b. If I do an echo of these, I am getting null (or a space, can't tell).

The current output of

 tail -2 http.txt | tr "\\n" " "

Is showing as: "48 36 "
Without the quotes of course. So it seems like it may not be properly removing the spaces perhaps? Not sure.

Thanks again

Your shell is likely running the read in a subshell. The variables are set there, but unset when you try to use them in the parent shell. You could try either writing the pipeline to a temp file and reading that, using process substution/here-string/here-doc to redirect the result of a command substitution into the read, or doing all the work with those variables in the subshell where read runs.

Regards,
Alister

Afraid I am still finding myself lost. Here is what I have right now. I tried creating a second file and doing the read on that, but still no variable being passed in my echo.


tail -2 filename.txt | tr "\n" " " > filename2.txt
tail filename2.txt | read a b
echo $b
if [ $a -gt 400 ] && [ $b -gt 400 ]; then
  touch filename.txt
fi

Try:

tail -2 filename.txt | 
{
  read a; read b
  echo $b
  if [ $a -gt 400 ] && [ $b -gt 400 ]; then
    touch filename.txt
  fi
}

That did the trick. Thanks Scrutinizer! And of course, thanks again to the others who provided input. Have a good day.