On Fri, Oct 29, 2021 at 07:37:13AM +0200, Léa Gris wrote:
> A safe way to replace:
> test -v "$USER_INPUT"
>
> Would be:
> test "${USER_INPUT@Q}"
>
> But it is not backward-compatible with older bash versions.
test -v is fairly recent as well. That was introduced in 4.2, and the @Q
syntax in 4.4.
I would suggest a three-step validation:
isvar() {
[[ $1 = LC_ALL ]] && { test -v "$1"; return; }
local LC_ALL=C
[[ $1 = [a-zA-Z_]*([a-zA-Z0-9_]) ]] || return 1
test -v "$1"
}
The forced-on extended globs inside [[ began with 4.1, and test -v in 4.2,
so this one requires bash 4.2 just like the original.
This one intentionally returns false for subscripted arrays, e.g.
isvar 'x[1]'. If you don't like that, change the extended glob to
suit yourself. Do note that test -v 'a[i]' requires bash 4.3.