28

I am trying to ls some files with a pattern in a directory. I only want to scan the first level not recursive.

My script:

for i in $(ls $INCOMINGDIR/*$BUSSINESSDATE*)
do
  echo $i;
done

Above command scan recursively. How can make it only to scan the first level directory?

Sas
  • 1,083

2 Answers2

62

Don't parse ls. Also don't use ALL_CAPS_VARS

for i in "$incoming_dir"/*"$business_date"*; do

Interactively, ls has a -d option that prevents descending into subdirectories:

ls -d $INCOMINGDIR/*$BUSSINESSDATE*
glenn jackman
  • 85,964
  • Thanks for the info, I am going to start creating files with new lines in the name just to annoy sysadmins now. – Petah Jan 16 '15 at 04:27
  • That's why the smart sysadmin/programmer uses "${i}". You never know what might be in i. – Ricky Jan 16 '15 at 06:36
  • @Petah: or someone with bad intentions could create a file named my_file.doc[newline]another_persons_file.doc and hope that some scripts may try to "rm" what it sees as 2 filenames... Glenn's link is a must read (on mywiki.wooledge.org, everyone should read the whole faq, and also the pitfalls page) – Olivier Dulac Jan 16 '15 at 09:27
  • 2
    cool. i didn't know the -d option! – dokaspar May 16 '18 at 08:04
  • Great! This works for simpler things too. Such as list all dot-prefixed files: ls -d .* – Wassadamo Aug 08 '19 at 00:11
8

There is no reason why this command should be recursive. But if $INCOMINGDIR/*$BUSSINESSDATE* matches a directory then the content of this directory is shown instead of the directory itself. But there would be no recursion beyond this level.

Use this command to avoid that effect:

ls -d "$INCOMINGDIR/"*"$BUSSINESSDATE"*

for ... in commands with ls output are risky.

In general find seems a better solution or

for i in "$INCOMINGDIR/"*"$BUSSINESSDATE"*
Hauke Laging
  • 90,279