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

Re: Weird set -u error



On Fri, Aug 26, 2022 at 08:17:10AM +0100, Tim Woodall wrote:
> $ cat Makefile.test
> SHELL := /bin/bash -u

WHY?!

> Why do I get that unbound variable error?

Because you turned on set -u in a place where the code had not been
adjusted to account for set -u's foibles.

set -u breaks scripts.  It's not as bad as set -e (nothing is that bad),
but it's still a dramatic change to the shell's behavior, and some
perfectly legitimate code *will* break.


On Fri, Aug 26, 2022 at 10:01:06AM +0200, Thomas Schmitt wrote:
> According to a comment in /etc/bash.bashrc it tests for emptiness of PS1
> in order to detect non-interactive shell sessions:
> 
>   # If not running interactively, don't do anything
>   [ -z "$PS1" ] && return
> 
> It should rather test for the variable being set, rather than being empty.

If you're testing whether a shell is interactive, the *proper* way is
to check for the presence of "i" in the "$-" special parameter:

case $- in *i*) :;; *) return;; esac

Or, bash only:

[[ $- = *i* ]] || return

Testing whether PS1 is set is a *hack* and it will fail (giving false
positives) if the user has exported the PS1 variable.  Which some people
do.

>   $ [ -z "${PS1:+x}" ] && echo "empty"

The ":" gives a positive result if the variable is defined but empty,
which may not be what you want.  Dunno, hard to guess why anyone would
want an empty PS1 variable, but I suppose it's possible.  People do weird
stuff all the time.


On Fri, Aug 26, 2022 at 11:04:25AM +0200, Thomas Schmitt wrote:
> tomas@tuxteam.de wrote:
> > Why {PS1:+x} rather than {PS1:-}?
> 
> It seemed to be the nearest suitable variation which was similar to the
> proposal
>   [ ${var+x} ]

You *should* still use quotes here.  Yeah, you might be thinking, the
only possible expansions are the empty string or "x", and it handles
both of those correctly, but it's still a matter of principle and good
habits.  By omitting the quotes, you're forcing the shell to perform
word splitting and globbing steps on the result, which actually makes
it run more slowly, even when those steps don't change the result.


Reply to: