1

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".

2
  • If you are using C to write to the file, wouldn't it be quicker to use C to read the file and compare the values?
    – iglvzx
    Commented Nov 18, 2011 at 7:21
  • How a shell script would extract that two-digit number depends on the format of the number and the structure of the file. It the number represented as two ASCII digits? Are those two digits the only contents of the file?
    – garyjohn
    Commented Nov 18, 2011 at 7:37

1 Answer 1

4

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.

2
  • 2
    If the file only contains one line containing the number, in bash you can write val=$(< c.txt). That's a bash shortcut for val=$(cat c.txt) Commented Nov 18, 2011 at 16:45
  • @glennjackman Thanks, that's much more concise. I added it to the answer.
    – slhck
    Commented Nov 18, 2011 at 17:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .