AishwaryaKulkarni AishwaryaKulkarni - 10 months ago 30
Bash Question

comparing a number with a variable in shell if command

I have a variable that I am storing as

upstream_introngap=$(awk '$3==$start-1 && $4 ~/$geneid/' File | awk '{print $3-$2}')

and using it in the code as

if [ "$upstream_introngap" -lt "100" ] ; then

However I am getting an error

[: : integer expression expected

I am trying different combinations but I am unable to get the right comparison expression, is the problem here the variable or the expression/number that is being compared with?
For instance

grep -w ENSG00000007237:I2 File
chr17 9964697 10017758 ENSG00000007237:I2 -
awk '$3==10017758 && $4 ~ /ENSG00000007237/' File | awk '{print $3-$2}' for

the above line
I want to compare this number (53061) to see if it's less than 100

Answer Source


upstream_introngap=$(awk -v s="$start" -v id="$geneid" '$3==s-1 && $4~id {print $3-$2; exit}' File)
if [ "$upstream_introngap" -lt "100" ]; then
    echo less than
    echo greater or equal

With this as the sample file:

$ cat File
chr17   9964697 10017758    ENSG00000007237:I2  -

The script produces this output:

$ bash script
greater or equal


  1. start and geneid are shell variables. The options -v s="$start" and -v id="$geneid" assign those shell variables to awk variables.

  2. There is no need for two awk commands. A single command can select the line and perform the subtraction.

  3. The expression $4~id is true if the fourth field matches id. In this context, id is treated as a regular expression. If id contains any regex-active characters, such as ()*+[], the results may not be what you expect.