Re: Bash scripting question

From: Chris F.A. Johnson (cfajohnson_at_gmail.com)
Date: 11/29/04


Date: 29 Nov 2004 07:22:45 GMT

On Mon, 29 Nov 2004 at 05:32 GMT, Lord Williams wrote:
> On Mon, 29 Nov 2004 00:33:57 +0000, Chris F.A. Johnson wrote:
>
>> On Sun, 28 Nov 2004 at 23:20 GMT, Wiseguy wrote:
>>> Wiseguy <noone@all.com> mumbled in
>>> news:Xns95AF6CE44161Enooneallcom@216.65.98.75:
>>>
>>>> "Lord Williams" <lordwill@quik.com> mumbled in
>>>> news:pan.2004.11.28.08.09.47.347137@quik.com:
>>>>
>>>>> I am reading :
>>>>>
>>>>> Mendel Coopers : Advanced Bash - Scripting Guide:
>>>>> An in-depth guide exploration of the art of shell scripting
>>>>>
>>>>> I was refered to this guide by someone here... and I am enjoying it
>>>>> ....
>>>>>
>>>>> anyways
>>>>>
>>>>> what do I do if I need to save the result of a return
>>>>> value from my compiled C programs from the return or exit function,
>>>>> for later uses in my script file?
>>>>>
>>>>> Is there a example that I could find in the guide?
>>>> cat input | grep "hello" > /dev/null
>>>> $rv=$?
>>>> # just saved the grep return value in $rv
>>>
>>> oops...
>>>
>>> rv=$?
>>>
>>> putting $ in front of the lvalue is a perl thing
>>
>> And putting "cat FILENAME |" in front of grep is a UUOC thing. :)
>>
>> grep "hello" FILENAME > /dev/null 2>&1
>> rv=$?
>
> So let me get this straight...
>
> rv ; means the return value from my program
>
> and it is assigned to $?
>
> but in my script if I have
>
> ~/programs/myprogram;
>
> I dont see how the return value from myprogram goes to rv=$?

   You have it backwards. The shell puts the return value from the
   last command or pipeline in the special variable $?. In the snippet
   above, that value is assigned to the variable rv, so that you do
   not lose it when you execute another command.

> And the other question is can I use it to check the return values of Linux
> commands if they fail
>
> for instance:
>
> cd directorydoesntexist
> bash: cd: directorydoesntexist: No such file or directory
>
> is there a way for linux to silently tell my bash script that the
> directory doesnt exist through a if conditional ?

if cd directorydoesntexist 2>/dev/null
then
  echo SUCCESS
else
  echo FAILURE
fi

     Or:

cd directorydoesntexist 2>/dev/null || echo FAILURE

     Or:

cd directorydoesntexist 2>/dev/null
if [ $? -ne 0 ]
then
   echo failure
fi

     Or.............

> And can I use this method for other commands in the linux OS to see if
> they fail?

     Yes.

> Some of my programs are returning a -1 to the OS and thats not
> supposed to happen according to the C standard. Is linux changing
> my return value?

     Under what circumstances is it returning -1? What command are you
     using?

-- 
	Chris F.A. Johnson                      http://cfaj.freeshell.org
	=================================================================
                Everything in moderation -- including moderation

Quantcast