Last Updated: February 25, 2016
·
12.75K
· killwing

Pass arguments with spaces to a command in Bash

Sometimes you want to pass complex arguments to a command. Usually when you constructing a command based on information that is only known at run time.
For example, ls arguments with spaces:
ls -hlF "my code" "my docs"

If you execute this command directly in bash, it's fine. Because the spaces are well quoted.
If you assign this string to a variable in a bash script and execute it, it'll fail to find these directories.
The solution is to convert arguments from string to array, which is explained here: I'm trying to put a command in a variable, but the complex cases always fail!

So i write a bash function to convert arguments from string to array for convienience (use double quote for arguments' spaces).

returnVal=()
convertArgsStrToArray() {
    local concat=""
    local t=""
    returnVal=()

    for word in $@; do
        local len=`expr "$word" : '.*"'`

        [ "$len" -eq 1 ] && concat="true"

        if [ "$concat" ]; then
            t+=" $word"
        else
            word=${word#\"}
            word=${word%\"}
            returnVal+=("$word")
        fi

        if [ "$concat" -a "$len" -gt 1 ]; then
            t=${t# }
            t=${t#\"}
            t=${t%\"}
            returnVal+=("$t")
            t=""
            concat=""
        fi
    done
}

To use:

lsArgs='-hlF "my code" "my docs"'
convertArgsStrToArray $lsArgs
ls "${returnVal[@]}"

Source: https://gist.github.com/4033179