Skip to content

Instantly share code, notes, and snippets.

@dutc
Created February 10, 2023 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/e7dfe62fecfbd6f5bbc6901bc6cda93d to your computer and use it in GitHub Desktop.
Save dutc/e7dfe62fecfbd6f5bbc6901bc6cda93d to your computer and use it in GitHub Desktop.
Constructing an array of arbitrary filenames in Zsh using `find`
#!/bin/zsh
script() {
typeset -A expected=(
a 0
b 1
c 5
"d d" 10
)
mkdir -p "${(@k)expected}"
for dirname num_entries in "${(@kv)expected}"; do
for ((i=0; i < $num_entries; i++)) touch "${dirname}/file $i"
done
typeset -A actual=()
typeset -a filenames=()
for dirname in "${(@k)expected}"; do
filenames=( ${(@0)"$(find "$dirname" -mindepth 1 -type f -print0)"#$'\0'} )
actual[$dirname]="${#filenames}"
done
for dirname in "${(@k)actual}"; do
act="${actual[$dirname]}"
exp="${expected[$dirname]}"
(( $act == $exp )) && res=✓ || res=✗
printf "%s %-4s %3d = %3d\n" "$res" "$dirname" "$act" "$exp"
done
}
script="$(sed -r 's/^[ ]{4}//' <<< "#!/bin/zsh"$'\n'"$(whence -f script | head -n -1 | tail -n +2 | expand -t 4 )")"
typeset -a bwrap_flags=(
--ro-bind / /
--tmpfs ~
'--ro-bind-data <(<<< "$script")(:t) ~/script.zsh'
)
eval "bwrap ${(*)bwrap_flags} zsh script.zsh"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment