rmyorston / busybox-w32

WIN32 native port of BusyBox.
https://frippery.org/busybox
Other
670 stars 124 forks source link

[QUESTION] Parametrize output descriptor #412

Closed ale5000-git closed 2 months ago

ale5000-git commented 4 months ago

Hi, since in some cases I want to change where the output go I wonder if this is POSIX compliant and really portable:

send_output()
{
  echo 1>&"${1:?}" "${2:?}"
}

send_output 1 'Prova 123'
send_output 2 'Prova 345'
avih commented 4 months ago

I think it's valid that word can be expanded. POSIX says:

The redirection operator: [n]>&word shall duplicate one output file descriptor from another, or shall close one. If word evaluates to one or more digits, the file descriptor denoted by n, or standard output if n is not specified, shall be made to be a copy of the file descriptor denoted by word; if the digits in word do not represent a file descriptor already open for output, a redirection error shall result; see Consequences of Shell Errors. If word evaluates to '-', file descriptor n, or standard output if n is not specified, is closed. Attempts to close a file descriptor that is not open shall not constitute an error. If word evaluates to something else, the behavior is unspecified.

Though it says here "word evaluates", while typically when expansion is involved it says something like "word is subject to tilde expansion, parameter expanstion, ...", which it does not say here, so not 100% sure.

But you can always use eval (carefully), e.g. eval "myfunc >&$whatever"

ale5000-git commented 4 months ago

Is there anyone else that has tested the code (my code, not eval because it likely has a lot of sided effects) in many shells (especially old ones)?

rmyorston commented 2 months ago

it says something like "word is subject to tilde expansion, parameter expanstion, ...", which it does not say here

To avoid needless repetition they define the expansions in the introductory part of 2.7:

If the redirection operator is "<<" or "<<-", the word that follows the redirection operator shall be subjected to quote removal; it is unspecified whether any of the other expansions occur. For the other redirection operators, the word that follows the redirection operator shall be subjected to tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal. Pathname expansion shall not be performed on the word by a non-interactive shell; an interactive shell may perform it, but shall do so only when the expansion would result in one word.

So we should be fine.

Is there anyone else that has tested the code (my code, not eval because it likely has a lot of sided effects) in many shells (especially old ones)?

The oldest shell I had ready access to is the one from Version 7 UNIX in V7/x86. But it's far too old to understand your code.

The next oldest was bash 1.14 from 2000, where it works as intended.

ale5000-git commented 2 months ago

Thanks to both for the help.