Script Execution Order

Hi,

I have two scripts which are mentioned in execute.sh

more execute.sh
./script1.sh   //line 1  should not return error
./script2.sh   //line 2  may return error
./script2.sh   //line 3  should not return error

Condition: I want script1.sh to complete before starting script2.sh (line 2) and script2.sh (on line 2) to complete before starting the script2.sh (on line 3)

Also there should be no errors in execution of line 1 and line 3 scripts while i expect errors returned in execution of line 2. Thus, i need a check at the end of the three lines if line 1 or line 3 returned errors (should display what returned error) execute.sh failed or else execute.sh was successful.

Can you please help ?

This is normally the case. If your scripts contain no sort of exquisite process management features (sending parts of themselvs into background, using nohup or the like) they way you wrote it script1 should be executed, then, upon its completion, script2 should be started, etc..

What makes you think this is not the case?

You can check the error code of a (any) process by querying the variable "$?", which is set after the completion of every command. Notice, though, that every other command re-sets this. For instance:

some_command
echo $?

will show the error returned by that command, but

echo "$(some_command | grep <something>)"
echo $?

will not. In fact it will display the error returned from the (first) echo command, which is most probably 0.

There are also other commands which use the error code returned from a process:

if some_command ; then
     echo "some_command returned error 0"
else
     echo "some_command returned an error >0"
fi

"if" evaluates the return level from the command (which can be a single command or some compound, like a pipeline) and executes the "then"-branch if this returns 0, otherwise the else-branch. Substitute "some_command" with "/bin/true" or "/bin/false" (two commands, which always return 0 and 1 respectively) to see the effect.

Another caveat is that scripts notoriously "forget" to set an error code. For a script to set an exit code you need to explicitly mention it with the exit-statement. This, for instance:

#! /bin/ksh

some_command
other command

exit

will always exit with 0, regardless of what the commands return. A script returning an error would look like this:

#! /bin/ksh

typeset -i iErrLvl=0

if ! some_command ; then
     iErrLvl=1
     print -u2 "Error in some_command"
else
     if ! other command ; then
          iErrLvl=2
          print -u2 "Error in some_command"
     fi
fi

exit $iErrLvl

This will execute "some_command" and return 1 if it fails, but if it succeeds it will also execute "other_command" and return 2 if this fails. If both succeed it will return 0.

I hope this helps.

bakunin