Need Help in Script

Hi Team,

Please help me to resolve the error in my script

[root@selvahost ~]# echo $0
-bash


num=`wc -l /root/demp/hehe.txt`
[root@selvahost ~]# echo $num
6 /root/demp/hehe.txt


cat backtickwithif.sh

#! /bin/bash
num=`wc -l /root/demp/hehe.txt`
echo $num
#if [ $num -gt 150 ]
if [ "$num" -gt "150" ]
then
echo "Condition Success"
else
echo "Condition failed"
echo ; fi


 ./backtickwithif.sh
6 /root/demp/hehe.txt
./backtickwithif.sh: line 6: [: 6 /root/demp/hehe.txt: integer expression expected
Condition failed

If i use other condition in the script if [ $num -gt 150 ] then I get different error message

 ./backtickwithif.sh
6 /root/demp/hehe.txt
./backtickwithif.sh: line 5: [: too many arguments
Condition failed

Hi, try:

num=$(wc -l < /root/demp/hehe.txt)

By using the redirect, variable num will only contain the number. Otherwise variable num will contain both the number and the filename, which leads to the errors.
I used a different form of command substitution (which I think is preferable), instead of backquotes.

1 Like

Hi - you probably don't need this now, but here is another way :-

num=`cat testfile | wc -l`
echo $num
if [ $num -gt 150 ]
then
  echo "Condition Success"
else
  echo "Condition Failed"
fi

This results in the following output when the input file contains 6 lines :-

[root@cooker test1]# ./chkfile.run
6
Condition Failed