Linux – Shell script to read value from a file and compare it to another one

linuxshell-script

I have a C program which puts one unique value inside a test file (it would be a two digit number). Now I want to run a shell script to read that number and then compare with my required number (e.g. 40).

The comparison should deliver "equal to" or "greater".

For example: The output of the C program is written into the file called c.txt with the value 36, and I want to compare it with the number 40.

So I want that comparison to be "equal to" or "greater" and then echo the value "equal" or "greater".

Best Answer

That's pretty basic, but unless you specify more, I don't know what else to add.

Just read the first line from the file, save it as a variable, and use simple comparisons like -gt (greater than) or -eq (equal to) to get your desired output. You can of course switch $val and $comp here, depending on what you really want.

#!/usr/bin/env bash
val=$(< c.txt)
comp=$1
if [[ "$val" -gt "$comp" ]]
  then echo "greater"
elif [[ "$val" -eq "$comp" ]]
  then echo "equal"
fi

Here, c.txt is your input file, and it is assumed that it only contains one line. The value you compare against is read as an argument, therefore you should call this script as:

./script.sh 40

Anyway, I'd highly recommend to read the Advanced Bash Scripting Guide.

Related Question