I wanted to create a script that executes the ls command with the provided arguments. Why isn't it working? I tried running it with for example -R, then it echoes (I echoed the same thing for comparison):

    ls "-R"

but says that it cannot access "-R": no such file or directory. But when I execute ls "-R" in the terminal, it works.

The script itself:


while [[ $# -gt 0 ]]
    text+=' "'


echo 'ls "-R"'

echo $text
  • ls "$@" will run ls with all arguments in the positional parameters.
    – mikeserv
    Mar 23 '14 at 19:45

The wrong quoting is the problem. " does not quote (and, which is the problem here, does not get removed!) if it is contained in a variable. Exception: eval $text

You should assign the parameters to an array and use ls "${vars[@]}" or ls "$@" instead.

Compare the two calls:

set -x
ls -l
ls "-l"
set +x
  • FYI, I added "eval" before "$text" and it's working! Thanks, man! And the one below, thanks too!
    – Darge Elar
    Mar 23 '14 at 19:22

That's not how quoting work in bash. When entering

ls "-R"

quotes removal happens on the command, so the command becomes

ls -R

If, on the other hand, if you set

text='ls "-R"'

and run $text, the quote removal does not happen. See man bash under EXPANSIONS:

After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the above expansions are removed.

" here resulted from parameter expansion, so it is not removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.