Results 1 to 4 of 4
Hello all,
I am writing a very simple bash script but I can't figure out why it is not working. I am just searching a file for a string and ...
- 01-05-2011 #1Just Joined!
- Join Date
- Jan 2011
- Posts
- 2
Very simple bash script ... However can't figure it out
Hello all,
I am writing a very simple bash script but I can't figure out why it is not working. I am just searching a file for a string and evaluating the return values using if - elsif. There are three possible values 0 (string found), 1 (string not found) and 2 (file not found).
However, for some reason, when the return code is 2, i.e. the file hello.txt does not exist (and I have checked that the return code is 2 in the terminal), the script is not getting into the second elsif as expected, but in the first (return code 1).
I believe the problem is that evaluating the conditions is making the $? to change its value. Actually, assigning $? to a variable and then comparing using this variable does the trick ... (i just found the solution myself
) Anyway, why $? works in that way ? Is this the only workaround to this problem ?
Cheers
Code:#!/bin/sh grep hello hello.txt > /dev/null if [ $? -eq 0 ]; then echo "Text found" elif [ $? -eq 1 ]; then echo "Text Not found" elif [ $? -eq 2 ]; then echo "File does not exist" else echo "other error" fi
Last edited by MikeTbob; 01-05-2011 at 11:45 AM. Reason: Added Code Tags
- 01-05-2011 #2Just Joined!
- Join Date
- Dec 2010
- Location
- India
- Posts
- 45
that is because $? hold the return status of immediate executed command
after grep hello hello.txt > /dev/null
is executed the $? value is 2 if the file doesn't exist . but immediately after that the script is executing if command which results the change of value of $? where you will get the return status of if statement but not grep statement .
- 01-05-2011 #3Just Joined!
- Join Date
- Jan 2011
- Posts
- 2
yes, that makes sense to what I found
Thanks
- 01-05-2011 #4
You can only evaluate whether the text is found if the file is found. Thus you need to check for the file first, and only check whether the text is found if the file exists. Obviously the text won't be found if the file isn't found.


Reply With Quote