[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Fwd: Undocumented behaviour of 'set -u' - errors when variable IS de
From: |
Greg Wooledge |
Subject: |
Re: Fwd: Undocumented behaviour of 'set -u' - errors when variable IS defined but non-number is used in numeric comparisons |
Date: |
Fri, 15 Nov 2024 15:02:50 -0500 |
On Fri, Nov 15, 2024 at 20:52:00 +0100, #!microsuxx wrote:
> try declare -i num=not
hobbit:~$ bash
hobbit:~$ set -u
hobbit:~$ declare -i num=not
bash: not: unbound variable
Again, this creates an arithmetic expansion context, so the string
"not" is treated as an unset (unbound) variable and triggers the
error when -u is in effect.
The OP either needs to turn off -u, or stop evaluating variables that
may contain words inside math contexts. Perhaps what they really
need is *input validation*. If you receive a value and store it in
a variable that's supposed to contain a number, you should verify that
it actually is a number before you use it.
<https://mywiki.wooledge.org/BashFAQ/054> has tips for validating numbers.
<https://mywiki.wooledge.org/CodeInjection#Arithmetic_Expansion>
demonstrates why it's *vital* to validate inputs before using them
in bash's arithmetic.