X-Git-Url: https://git.stderr.nl/gitweb?p=matthijs%2Fupstream%2Fbackupninja.git;a=blobdiff_plain;f=lib%2Farray.in;fp=lib%2Farray.in;h=066e963c326f18c47dabb2d3147863f7f2c4a2a7;hp=0000000000000000000000000000000000000000;hb=2bca36e49ce95bca1d2bb2d7aadb7fcd093b59fd;hpb=2fc3bd4d5d981eb2e5b4e7f31047c8f24b877c9e diff --git a/lib/array.in b/lib/array.in new file mode 100644 index 0000000..066e963 --- /dev/null +++ b/lib/array.in @@ -0,0 +1,46 @@ +# -*- mode: sh; sh-basic-offset: 3; indent-tabs-mode: nil; -*- +# vim: set filetype=sh sw=3 sts=3 expandtab autoindent: + +# Append $2, $3, etc. to the array variable pointed to by $1. +# For example: +# $ foo=(a) +# $ append foo b c +# $ echo "${foo[@]}" +# a b c +# It can be used to concatenate arrays too: +# $ append foo "${foo[@]}" +# $ echo "${foo[@]}" +# a b c a b c +function append { + # Get the variable name, so $@ only contains the elements to append + varname="$1" + shift + # Here we quote the entire string passed to eval to prevent the + # normal braces from creating parse errors. We also escape the $ in + # the value, to ensure no stuff like pathname expansion is + # performed on it (since $@ could contain anything). We can safely + # expand $varname before evaluation, since we can be pretty sure that a + # valid variable name does not contain any weird stuff like backticks + # or tildes. + # We need this eval in the first place to do indirect assignment and + # indirectly reference the old value. The former could be done using + # some export hack, which is perhaps a bit more elegant, but the + # latter is not possible without eval it seems (there is the ${!var} + # syntax, but stupid bash has assigned a different meaning to + # ${!var[@]}, so you can't indirectly reference an array... + eval "$varname=(\"\${$varname[@]}\" \"\$@\")" +} + +# Does $1 occur in $2, $3, etc.? +function in_array { + search=$1 + shift + for i in "$@"; do + if [ x"$i" == x"$search" ]; then + # Found + return 0 + fi + done + # Not found + return 1 +}