~$ echo $(ls)  
arguments.txt cecho.sh Desktop Documents Downloads example.txt Music Pictures Public     
~$ echo $(ls "*.txt")  
ls: cannot access *.txt: No such file or directory  

Why does the 2nd subshell command fails?


Remove the quotes around *.txt and it should work. With quotes shell will look for the literal filename *.txt. To explore/experiment, try creating a file with name *.txt as touch '*.txt' and repeat the command.

  • 6
    Note that double quotes (at least in bash and similar shells like zsh) are not the same as single quotes! For example, parameter expansion ($foo) is done inside double quotes, but not single quotes. Feb 10 '14 at 5:44

In the same way that you can't run ls "*.txt" in a normal shell, you can't run it in a subshell either. When you put *.txt in quotes, you made ls search for a literal file called *.txt when instead you should be doing this:

$ echo $(ls *.txt) # => file.txt otherfile.txt

A better way to do this is to not use ls at all.

$ echo *.txt # => file.txt otherfile.txt
  • 7
    +1 for removing the redundant ls. Feb 10 '14 at 5:41
  • 3
    Nitpicking: You can run ls -l "*.txt". Or at least I can. I do it not often, but when I do, it usually tells me that it couldn't find *.txt ...
    – Ingo
    Feb 10 '14 at 15:18
  • @lngo: That's in the OP's post too Feb 11 '14 at 15:52

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.