3

I have 2 lines of code

1) With the following code:

for i in `ls *.properties`; do cat $i; done

I get the error:

cat: file_name.properties: No such file or directory.

2) On the other hand:

for i in *.properties; do cat $i; done

Works fine!

I thought both were the same. Can someone help me understand the difference between the two? Using bash shell.

8
  • 2
    does your filename contain a space? Commented May 15, 2012 at 20:50
  • No it does not. Names are separated by underscores. Commented May 15, 2012 at 20:52
  • Please show an actual example. It doesn't have to be your real file names if you don't want to share, but something that demonstrates the problem you're seeing would be helpful. Commented May 15, 2012 at 20:53
  • 2
    The bare glob is correct anyway. You should never do for i in `ls`. It might also be helpful to do if [[ -f $i ]]; then cat "$i"; fi to make sure you're only getting files and not directories. Note also that the variable should be quoted as I have done. Commented May 15, 2012 at 21:04
  • 2
    @khaled_webdev: That brings up lots of things, some incorrect. Can you be more specific what to search for on that page? Commented May 15, 2012 at 21:07

2 Answers 2

6

What does the following command print?

cat -v <<< `ls *.properties`

I guess the problem is, that ls is a strange alias, e.g. something like

ls='ls --color'

Edit: I have seen this before. The alias should be: alias ls='ls --color=auto'

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you nosid. There was an alias exactly as you mentioned. Appreciate it.
@KarolyHorvath: Or even shorter: alias ls
0

Most probably there is a directory which matches *.properties. Then ls will output the files in this directory without the directory name. Then the cat will not find the given filename.

So please check, whether file_name.properties is in the actual directory or in some subdirectory.

EDIT

To reproduce the problem you can try this:

# cd /tmp
# mkdir foo.properties
# touch foo.properties/file_name.properties
# for i in `ls *.properties`; do cat $i; done
cat: file_name.properties: No such file or directory

4 Comments

nice idea but in this case he would first see cat: directoryname:: No such file or directory. (note the double colon)
@KarolyHorvath you won't, because ls dir will output the contents of the directory but not the text dir itself. Hence cat wont see this name and cannot produce the output you proposed.
@Karoly, neat, I've never noticed that before; cat: rc0.d:: No such file or directory. :)
@A.H.: that's because you did the ls with only one argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.