On 03/22/2017 04:12 AM, Jean Delvare wrote:
> command | while read line
> do
> if <condition>
> then
> ex
> it 42
> fi
> process $line
> done
>
> if [ $? -eq 42 ]
> then
> exit
> fi
Splitting things into functions sometimes helps. Possibly just one:
~ $ mksh <<\EOF; echo "status: $?"
# Take a command and read a random number of lines
function reader {
if ${1+'false'}; then
while read -r line; do
if (( ! (RANDOM % 10) )); then
echo
return 42
fi
print -rn -- "$line "
done
else
"$@" 2>/dev/null | reader || exit
fi
}
reader yes I read my mind
EOF
I read my mind I read my mind I read my mind I read my mind
status: 42
Coprocesses are probably the most direct ksh alternative to <() / >()
and lastpipe. Example (mksh / ksh93):
~ $ mksh <<\EOF; echo "status: $?"
LC_CTYPE=C tr -cd "[:digit:]" </dev/urandom |&
while IFS= read -rN 1 x; do
if (( !x )); then
exec 3>&p 3>&- </dev/null
echo
exit 42
fi
print -rn -- "$x "
done <&p
EOF
1 7 5 6 1 1 7
status: 42
Only mksh and ksh93 have mostly compatible syntax though, which
unfortunately involves an operator (|&) that you can't easily simulate
in bash or zsh and conflicts with a totally different operator in at
least bash. In the end, To make it compatible you have to write a wrapper
function that ends up looking pretty much like Bash's `coproc' keyword.
>
> I was wondering if there is any other trick you can suggest that would work
> in mksh?
I usually nag at Thorsten til I get $FEATURE. Worked for ksh93.
https://www.mail-archive.com/[email protected]/msg00900.html
Optionally disabling the subshell at runtime is useful for many things.