Reputation: 3
temp.txt is a file with a single line:
1.2034 3.2323 4.3121 5.1223
I have to do the following set of operations multiple times with different values so I have it all in a loop. Given below is the main issue I am facing and would appreciate some help solving.
v1=$(cut -d" " -f2 temp.txt);
v2=$(cut -d" " -f3 temp.txt);
v3=$(cut -d" " -f4 temp.txt);
v4=$(cut -d" " -f5 temp.txt);
#$v1, $v2, $v3, $v4 contain the above 4 values (1.2034, 3.2323, 4.3121, 5.1223). I have verified that. I want to compare their values, but when I do, I get an error because of incorrect syntax.
if [ "$v1" -gt "$v2" | bc ] && [ "$v3" -gt "$v4" | bc ]; then
echo Yes
fi
I get this error:
line 6: [: missing `]'
File ] is unavailable.
Could someone please help me with my syntax? I have tried a few different things already and it didn't work. I have tried different combinations of brackets and spaces and both using bc and without bc.
Upvotes: 0
Views: 34
Reputation: 531798
You want to construct a valid bc
expression and pipe it to bc
, capture the output, then compare that to the expected result.
if [[ $(echo "$v1 > $v2" | bc) == 1 && $(echo "$v3 > $v4" | bc) == 1 ]]; then
echo Yes
fi
If bash
could do floating-point arithmetic (or if your values were actually integers), you could do the comparisons directly in bash
:
if [[ $v1 -gt $v2 && $v3 -gt $v4 ]]; then echo Yes; fi
or
if (( v1 > v2 && v3 > v4 )); then echo Yes; fi
A quicker way to populate your four variables is
read x1 v1 v2 v3 v4 x2 < temp.txt
(x1
and x2
are just variables whose value we don't really care about; the first field and any fields that might occur after the 5th thone.)
Upvotes: 1