[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to use PROMPT_COMMAND(S) without breaking other scripts

From: Martijn Dekker
Subject: Re: How to use PROMPT_COMMAND(S) without breaking other scripts
Date: Mon, 24 Aug 2020 17:58:27 +0100
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Thunderbird/68.11.0

Op 24-08-20 om 15:57 schreef Chet Ramey:
I sometimes think I should have stuck with converting PROMPT_COMMAND to
an array. Either way, there's going to be a transition, and maybe that
would have been the easiest.

Is it too late? I think that would actually be cleaner than adding a separate array, per Koichi's report.

One problem is that if a script does the obvious

    PROMPT_COMMAND+=("some command here")

if PROMPT_COMMAND is not yet set, then it starts adding at array index 0, so a subsequent traditional usage from some other script

    PROMPT_COMMAND="some command here"

would overwrite it. So array usage should not use the 0 index. To avoid using the 0 index, one possibility is:

    PROMPT_COMMAND[$(( ${#PROMPT_COMMAND[@]} + 1 ))]="some command here"

which, if PROMPT_COMMAND is unset, starts adding at index 1, not 0, and otherwise acts identically. However, 'set -u'/'set -o nounset' kills that. That option makes the ${#PROMPT_COMMAND[@]} expansion error out if there are no array elements (even though ${#@} works with no positional parameters). It's also an unwieldy command. So maybe that idea is not the best.

Another way to avoid using the 0 index, which is 'set -u' compatible, would be

    PROMPT_COMMAND+=("some command here")

The first command sets PROMPT_COMMAND[0] to the empty value if it doesn't exist yet, and otherwise leaves it unchanged. It's a bit of an ugly hack though.

But then, maybe it's best if bash itself just sets PROMPT_COMMAND[0] to the empty value on initialisation. IMO that would be a reasonably clean and reliable way to ensure a smooth transition.

Just my 2ยข,

- M.

||      modernish -- harness the shell
||      https://github.com/modernish/modernish
||      KornShell lives!
||      https://github.com/ksh93/ksh

reply via email to

[Prev in Thread] Current Thread [Next in Thread]