Operating System - HP-UX
1830241 Members
1427 Online
109999 Solutions
New Discussion

Re: Scripting problem: grouping and pipes

 
Andrew F Greenwood
Occasional Advisor

Scripting problem: grouping and pipes

Oh dear. I have a problem.

I have a number of scripts with grouped commands piping their output to mailx. Some of these commands are error trapped, and should exit the program. They aren't.

Try runnng the attached program, and then try it again after removing the " | cat -".

I hope someone can help me!
5 REPLIES 5
Rodney Hills
Honored Contributor

Re: Scripting problem: grouping and pipes

I think since you are using braces to group, that tells ksh to do the processes inline (not as a subprocess). As soon as you added the "| cat -", then ksh decided it needed to launch the list as a subprocess.

To adjust the script to not require the "cat -", then put the "false || errorfunc" within parenthesis. The man for ksh states that "||" has a higher precedence over ";"

-- Rod Hills
There be dragons...
Andrew F Greenwood
Occasional Advisor

Re: Scripting problem: grouping and pipes

Thanks for replying so fast, but I'm not sure I followed you.

Could you attach a modified version of the script that does work?
Rodney Hills
Honored Contributor

Re: Scripting problem: grouping and pipes

Here you go-

#!/bin/ksh
set -x

error_func()
{
[[ -n "$@" ]] && print -u2 "$@"
exit 1
}

echo Start

{
echo Start of braces
( false || error_func )
echo End of braces
}

echo Completed successfully
exit 0
There be dragons...
Andrew F Greenwood
Occasional Advisor

Re: Scripting problem: grouping and pipes

I certainly think that you are right in what you are saying about inline versus sub-process. I had a feeling it might be something like that.

There are two things I need from this part of my script - one is that I need for the error within the braces (i.e. the false) to be trapped and to cause an exit -1 from the script - the second is that I need all stdout from the braces to be piped through to another command (in my script it is mailx, in the test example it is cat -.)
Rodney Hills
Honored Contributor

Re: Scripting problem: grouping and pipes

If I understand what you want-
1) execute commands piping output to mailx
2) if error in any command, then exit script with return status of -1

Using "trap", you could do the following-

#!/usr/bin/ksh
export oops=/tmp/oops$$
rm $oops >/dev/null 2>&1
(
set -e
trap "touch $oops" ERR
echo start
false
echo end
) | mailx user@host.com
# See if any errors in prev commands
if [[ -f $oops ]] then
rm $oops
exit -1
else
exit 0
fi

Anything more complicated you may want to study up on shell programming...

Good Luck

-- Rod Hills

There be dragons...