Ashish Ashish - 1 year ago 49
Bash Question

Unable to substract two variable in shell scripting

I am writing a script that's picking up two values from a file and then subtracting them.But I am unable to do substraction as it is throwing error.

res1= awk 'FNR == '${num1}' {print $1}' /home/shell/test.txt
res2= awk 'FNR == '${num2}' {print $1}' /home/shell/test.txt

res= $((res2 - res1))
echo $res

I also tried
expr = `expr $res2 -$res1`
but it didn't work. please help me so as to get the desired result.


your assignments for res1/res2 are wrong. It should be

res1=$(awk 'FNR == '${num1}' {print $1}' /home/shell/test.txt)

However, you can do it all in awk

$ num1=5; num2=2; awk -v n1=${num1} -v n2=${num2} 'FNR==n1{r1=$1;f1=1}
                                                    f1&&f2{print r1-r2; exit}' <(seq 5)