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 [ ]. Commented Nov 24, 2019 at 4:54

1 Answer 1

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.