Search code examples
bashshellquotingbackticks

Word splitting within backticks


What is the difference between line #2 and line #4 in the script ("foo bar" (without quotes) folder exists):

FOOBAR="foo bar"
echo `ls -la "$FOOBAR"`
args="-la \"$FOOBAR\""
echo `ls $args`

Output:

total 0 drwxr-xr-x 2 tervlad LD\Domain Users 68 15 ноя 11:47 . drwxr-xr-x 7 tervlad LD\Domain Users 238 16 ноя 18:01 ..
ls: "foo: No such file or directory
ls: bar": No such file or directory

How can I get line #4 working properly?


Solution

  • $FOOBAR is expanded in the assignment to args. Also quotes are interpreted before $ expansion, so quotes are literal parts of the expanded string.

    Just use an array.

    args=( "-la" "$FOOBAR" )
    ls "${args[@]}"