3

Suppose you want your script to take variables from environment:

#!/usr/bin/env bash
set -eu

if (( ${A-} )); then
    echo true
else
    echo false
fi

Arithmetic expansion seems to be more reasonable here to handle (empty), 0, 1 cases, or else:

if [ "${A-}" ] && [ "${A-}" != 0 ]; then

But then,

$ A='1 - 1' ./1.sh
false
$ A='B = 1' ./1.sh
true

So now you can basically change variables, which you generally don't want to allow. What would you suggest? How to process boolean flags taken from environment variables?

1
  • How was this an injection attack? Did you perhaps mean A='A = 1 - 1' ./sh? It doesn't work with the version that uses [ ].
    – konsolebox
    Nov 24 '19 at 4:54
1

If you're unsure if variable holds an int, you can validate its value:

#!/usr/bin/env bash
set -eu

vint() {
    local v
    for v; do
        if echo "$v" | egrep '[^0-9]' &> /dev/null; then
            printf '%s: %s: not an int\n' "$0" "$v" >&2
            exit 1
        fi
    done
}

vint "${A-}"
if (( ${A-} )); then
    echo true
else
    echo false
fi

This is as far as I could take it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.