The supplier sent a CSV
every night.

A small bash script
read it line by line
and skipped rows with nothing to order.

IFS=, read -r sku qty <<< "$line"

if [[ $qty -eq 0 ]]; then
continue
fi

No eval.

No unquoted command.

It looked safe.

Then one row arrived
with this in the quantity column:

x[$(touch /tmp/owned)]

And a file appeared
that nobody had asked for.

It could as easily
have been anything else
the attacker wanted to run.

Here is the mechanism.

Inside [[ ]],
the operands of -eq
are not compared as text.

They are evaluated
as arithmetic expressions.

The bash manual says so,
in one quiet sentence.

In an arithmetic expression,
a word that is not a number
is treated as a variable name.

a[...] is an array element.

To find which element,
bash expands the subscript.

Expansion includes
command substitution.

So $( ... ) runs.

The value of qty
was never executed as a command.

It was looked up
as a variable,
and looking it up
ran one.

The same evaluation happens in

(( qty > 0 ))

$(( qty * price ))

let and declare -i

and any array index
built from input.

Quoting does not help.

[[ "$qty" -eq 0 ]]
evaluates the same string.

The fix is to prove
it is a number first,
as text,
before arithmetic ever sees it:

if [[ ! $qty =~ ^[0-9]+$ ]]; then
echo "bad quantity: $sku" >&2
continue
fi

After that line,
qty can only be digits,
and digits are just numbers.

Do the same
for anything you feed into (( )):
fields from files,
headers from webhooks,
branch names in a pipeline.

Code review will not catch it either.

The line looks like
the safest line in the script.

Bash does not warn you.

It sees a word,
does its best to understand it,
and its best
includes running it.

Validate the shape.

Then do the maths.

– Serguey Asael Shinder