[TUHS] A few comments on porting the Bourne shell
Chet Ramey
chet.ramey at case.edu
Thu Jan 5 05:33:13 AEST 2023
On 1/4/23 11:15 AM, Dan Cross wrote:
> On Tue, Jan 3, 2023 at 11:16 PM Bakul Shah <bakul at iitbombay.org> wrote:
>> On Jan 3, 2023, at 7:31 PM, Dan Cross <crossd at gmail.com> wrote:
>>> On Tue, Jan 3, 2023 at 10:22 PM John Cowan <cowan at ccil.org> wrote:
>>>> Making shell scripts portable means not using pipelines, because given "foo | bar", kshNN and zsh execute foo in a subshell and bar in the top-level shell, whereas in other shells, both foo and bar execute in subshells. (For this reason, Posix allows either behavior.) Not having pipelines is a pretty drastic limitation.
>>>
>>> This came up at work just the other day:
>>>
>>> echo ' hi ' | sed 's/^ *//;s/ *$//' | read bummer
>>> echo $bummer
>>>
>>> The behavior varies between ksh, zsh, bash, sh. Yay.
>>
>> On this example sh, zsh, bash behave the same way on
>> freebsd. Rather than ban |, I think the lesson is to
>> *avoid* builtin commands in a pipeline that can affect
>> shell's environment. I only write /bin/sh scripts in
>> any case.
>
> Interesting. In my testing, `bash` was the odd man out:
>
> : doctor; zsh
> : doctor; echo ' hi ' | sed 's/^ *//;s/ *$//' | read bummer
> echo $bummer
>
> hi
> : doctor;
> : doctor; bash
> : doctor; echo ' hi ' | sed 's/^ *//;s/ *$//' | read bummer
> echo $bummer
>
> : doctor;
> exit
> : doctor; ksh
> : doctor; echo ' hi ' | sed 's/^ *//;s/ *$//' | read bummer
> : doctor; echo $bummer
> hi
> : doctor;
> : doctor; sh
> : doctor; echo ' hi ' | sed 's/^ *//;s/ *$//' | read bummer
> : doctor; echo $bummer
> hi
> : doctor;
> : doctor;
>
> That's on illumos.
On Illumos, /bin/sh and /usr/xpg4/bin/sh are both links to ksh93.
ksh88/ksh93 and zsh are the only shells that unconditionally run the last
element of a pipeline in the current shell. Bash will do it if job control
is not enabled and the `lastpipe' option is enabled.
It's usually not a problem, but you do have to be aware of potential side
effects.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU chet at case.edu http://tiswww.cwru.edu/~chet/
More information about the TUHS
mailing list