store last command exit status in variable in shell script

Hello All

My req is to store the exit status of a command in shell variable

I want to check whether the file has header or not
The header will contain the string
DATA_ACQ_CYC_CNTL_ID

So I am running the command

head -1 $i | grep DATA_ACQ_CYC_CNTL_ID

Now I have to check if header is there then I will print Header exist if not then header doesn't exist

So the below I put

 
output=$?
echo $output
if [ $output -eq 0 ]
then 
echo header in flat file exist
else 
Flat File $i has no header
fi

but the code is not giving expected result when header doesn't exist
Its not showing

 
Flat File $i has no header

Hi you missed a couple of things, try with these corrections:

#Here the command to execute

output=$?
echo $output
if [ "$output" -eq "0" ]
then 
      echo "header in flat file exist"
else 
      echo "Flat File $i has no header"
fi

Modify the line output=`echo $?`

Thanks for both of your reply but in case if condition fails the o/p is not
echo "Flat File $i has no header"

but Compare.sh[15]: Flat: not found

works fine for me ..

i="filename"
head -1 $i | grep DATA_ACQ_CYC_CNTL_ID
output=`echo $?`
echo $output
if [ $output -eq 0 ]
then
echo "header in flat file exist"
else
echo "Flat File $i has no header"
fi
else 
Flat File $i has no header

should be

 
else 
echo " File $i has no header "

---------- Post updated at 03:04 PM ---------- Previous update was at 03:03 PM ----------

you can check something like this also.

 
grep "DATA_ACQ_CYC_CNTL_ID" filename > /dev/null && echo "Header is there" || echo "Header is not there"

if your grep supports -q then no need to put > /dev/null

Thanks a lot everyone .its working fine now