akemko
akemko

Reputation: 55

Shell returns all files when regex doesn't match any file in directory?

I use below command in shell file and works fine in the directories that regex matches. Problem is, it lists all files when there is no match for regex. Anyone knows why it has this behaviour?
Are there anyway to avoid it?

find  . -type f -mtime +365 | egrep '.*xxx.yyy*.*'|grep -v "[^.]/" | xargs ls -lrt | tr -s " " | cut -d" " -f6-9

thanks for your time. Note: I m using this script with splunk forwarder on solaris 8.

Upvotes: 0

Views: 105

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328614

If the input of xargs is empty, then it will execute ls -lrt in the current folder.

Try xargs -i "{}" ls -lrt "{}" instead. That forces xargs to put the input arguments into a certain place in the command that it executes. If it doesn't have any input, it can't and will skip running the command at all.

If you have GNU xargs, you can use the switch --no-run-if-empty instead.

If that doesn't work, try to move all the greping into find, so you can use -ls to display the list of files. That will also avoid running the ls command if no file matches.

Upvotes: 2

Related Questions