Skip to content

Instantly share code, notes, and snippets.

@knirch
Created August 20, 2025 10:55
Show Gist options
  • Select an option

  • Save knirch/828e7b359d3f2171a75f9b6654868664 to your computer and use it in GitHub Desktop.

Select an option

Save knirch/828e7b359d3f2171a75f9b6654868664 to your computer and use it in GitHub Desktop.
unpacking? yield? idk. something.
#!/bin/bash
# shellcheck disable=SC2034
# shellcheck disable=SC2154
# Yeah, I don't think I can make it shellcheck safe
forin() {
local -n ref=$1
shift
while (($#)); do
printf -v "$1" "%s" "${ref[__forin_pos]}"
((__forin_pos++))
shift
done
if ((__forin_pos > ${#ref[@]})); then
unset __forin_pos
return 1
fi
return 0
}
haxx=(
foo 12
"bar bar bar" 47
baz 91
grault 0
)
while forin haxx who amount; do
echo "$who has $amount of something"
done
echo
while forin haxx who amount friend famount; do
echo "$who and $friend has $((amount+famount)) together"
done
foo has 12 of something
bar bar bar has 47 of something
baz has 91 of something
grault has 0 of something
foo and bar bar bar has 59 together
baz and grault has 91 together
@knirch
Copy link
Author

knirch commented Aug 20, 2025

yes, it's zsh envy.

knirch@falschgeld ~ % echo $0
zsh
knirch@falschgeld ~ % hax=(foo 1 bar 2 baz 3)
knirch@falschgeld ~ % for a b in ${hax[@]}; do echo $b $a; done
1 foo
2 bar
3 baz

@knirch
Copy link
Author

knirch commented Aug 20, 2025

or, just use the tools available

hax=(foo 1 bar 2 baz 3)
set -- "${hax[@]}"
while (($#)); do
	echo "$2 $1"
	shift 2
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment