Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question
    
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 Nov 18 '11 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 Nov 18 '11 at 7:37

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
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) –  glenn jackman Nov 18 '11 at 16:45
    
@glennjackman Thanks, that's much more concise. I added it to the answer. –  slhck Nov 18 '11 at 17:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.