2 ms·
Unfortunately it doesn't work if you forbid unbound variables with set -u. Like this (as suggested in the Unofficial strict mode article: https://news.ycombina
by kwhitefoot 5y ago
Unfortunately it doesn't work if you forbid unbound variables with set -u. Like this (as suggested in the Unofficial strict mode article: https://news.ycombinator.com/item?id=8054440 https://news.ycombinator.com/item?id=8054440):
$cat z
#!/bin/bash
set -u # fail if unset variable is used
if [[ -n ${COLODEBUG} && ${-} != *x* ]]
then
:() {
[[ ${1:--} != ::* ]] && return 0
printf '%s\n' "${*}" >&2
}
fi
echo hello
$./z
./z: line 10: COLODEBUG: unbound variable
$
The -n test should look like this:
if [[ -n ${COLODEBUG:-} && ${-} != *x* ]]
- c0l0 5y agoYou are right, this change makes the drop-in snippet more robust: If one issues `set -u` before trying or deciding whether to redefine `:` (which would also be the effect of invoking the interpreter with the `-u` option), the variant presented in the article breaks. If the shall-we-redefine-: check has already been performed before `-u` is in effect, the alternative implementation of `:` itself will work fine. It's kinda unfortunate this slipped through, because before I tried to "formalize" this little trick in the article yesterday, I definitely remember having used variants that guarded against this little nasty trap you now independently rediscovered ;) Would you mind me updating the article accordingly, and crediting your HN account name/profile in the changelog? Thanks a lot for your rigorous reading and very constructive feedback! :)
- kwhitefoot 5y ago> Would you mind me updating the article accordingly, and crediting your HN account name/profile in the changelog? No problem. I'm retired now so my name doesn't appear in changelogs as often as it used to!
- kwhitefoot 5y agoI have another couple of suggestions. The first suggestion is to add export -f : just before the fi so that it is available to scripts called from the main script. The second is to add local IFS=" " # Insulate : from changes to IFS before the printf. because if I didn't then each word of the comment would appear on a separate line like this: :: a b c instead of this: :: a b c the reason for this is that I had defined IFS="/n/t" as suggested by the Unofficial Strict Mode.