Skip to content

Comment on TIL: Some surprising code execution sources in bash

Comments

Unfortunately, there's a lot of gotchas in Bash like this. A lot of them are documented here: https://mywiki.wooledge.org/BashPitfalls, including the `test -v` case, which is #61. Some more code execution pitfalls are documented here: https://mywiki.wooledge.org/BashProgramming/05?action=show&r... including the `-eq` part (under Arithmetic Expansion).

Basically, the -v case was by design, so for `-v 'hash[$key]'`, "$key is expanded before the array subscript evaluation, and then the whole array plus expanded index is evaluated in a second pass". "Newer versions of bash (5.0 and higher) have a assoc_expand_once option which will suppress the multiple evaluations"

Note that the `-v` case doesn't really work the way one may infer from reading the OP:

$ key='$(cat /etc/passwd > /tmp/pwned)'
$ [[ -v 'x[$key]' ]]
bash: $(cat /etc/passwd > /tmp/pwned): syntax error: operand expected (error token is "$(cat /etc/passwd > /tmp/pwned)") *
[[ -v "${x[$key]}" ]]
bash: $(cat /etc/passwd > /tmp/pwned): syntax error: operand expected (error token is "$(cat /etc/passwd > /tmp/pwned)")
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.