Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable lost when redirecting output to logfile

Status
Not open for further replies.

130272

MIS
Mar 31, 2003
3
NL
I want to capture the output of several commands into a logfile. In between these commands, a value is assigned to a variable.

Example code 1:
----------
#!/bin/ksh
{
command1
command2
important_command3
exit_code=${?}
command4
} |tee ${LOGFILE}
if [ ${exit_code} -ne 0 ]
then mailx -s"Failure" ${RECIPIENT} <${LOGFILE}
fi
----------

When running the script the 'if' statement fails because ${exit_code} does not exist. However, when running the following example, the variable ${exit_code} is suddenly known and the 'if' statement does not present any errors:

Example code 2:
----------
#!/bin/ksh
{
command1
command2
important_command3
exit_code=${?}
command4
}
if [ ${exit_code} -ne 0 ]
then mailx -s"Failure" ${RECIPIENT} <${LOGFILE}
fi
----------

Does anyone have an idea why the variable get lost when 'tee-ing' the output into the logfile?
 
Yes, I have tried to export the variable but it didn't work.
 
Contrary to some documentation, a brace group doesn't always execute within the current environment. If you follow a brace group with | or &, it creates a subshell, just like parenthetical grouping does.

In your first case, exit_code is being defined in the subshell's environment, which the script has no access to.

One solution would be to use a flag file:

[tt]
#!/bin/ksh
{
rm /tmp/errflag > /dev/null 2>&1
command1
command2
important_command3
if [ ${?} -ne 0 ]
then
touch /tmp/errflag
fi
command4
} |tee ${LOGFILE}
if [ -e /tmp/errflag ]
then mailx -s"Failure" ${RECIPIENT} <${LOGFILE}
fi
[/tt]

Rod Knowlton

IBM Certified Advanced Technical Expert pSeries and AIX 5L
CompTIA Linux+
CompTIA Security+

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top