build argument lists containing whitespace build argument lists containing whitespace bash bash

build argument lists containing whitespace


There are (at least) two ways to do this:

  1. Use an array and expand it using "${array[@]}":

    bar() {    local i=0 args=()    for arg in "$@"    do        args[$i]="prefix $arg"        ((++i))    done    foo "${args[@]}"}

    So, what have we learned? "${array[@]}" is to ${array[*]} what "$@" is to $*.

  2. Or if you do not want to use arrays you need to use eval:

    bar() {    local args=()    for arg in "$@"    do        args="$args \"prefix $arg\""    done    eval foo $args}


Here is a shorter version which does not require the use of a numeric index:

(example: building arguments to a find command)

dir=$1shiftfor f in "$@" ; do    args+=(-iname "*$f*")donefind "$dir" "${args[@]}"