-1

I am writing a script where I need to list files without displaying them. The below script list the files while executing which I don't want to do. Just want to check if there are files in directory then execute "executing case 2". ls -lrt /a/b/c/ if [ $? != 0 ] then echo "executing case 2" else echo "date +%D' '%TNo files found to process" >> $LOG

Martini_geek
  • 629
  • 1
  • 5
  • 8
  • What are you asking? "Just want to check if there are files in directory" sounds like: http://stackoverflow.com/questions/5884885/how-to-specify-if-directory-not-empty-in-a-ash-shell-script but your script looks like you test whether a directory exists rather whether it is empty (in which case: http://stackoverflow.com/questions/59838/check-if-a-directory-exists-in-a-shell-script) – yankee Jan 28 '15 at 10:00

2 Answers2

0

Testing the return code of ls won't do you a lot of good, because it'll return zero in both cases where it could list the directory.

You could do so with grep though.

e.g.:

ls | grep .
echo $?

This will be 'true' if grep matched anything (files were present). And false if not.

So in your example:

ls | grep .
if [ $? -eq 0 ] 
then 
    echo "Directory has contents"
else
    echo "directory is empty"
fi

Although be cautious with doing this sort of thing - it looks like you're in danger of a busy-wait test, which can make sysadmins unhappy.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
0

If you don't need to see the output of ls, you could just make it a condition:

[ "$(ls -lrt a/b/c)" ] && echo "Not Empty" || echo "Empty"

Or better yet

[ "$(ls -A a/b/c)" ] && echo "Not Empty" || echo "Empty"

Since you don't care about long output (l) or display order (rt).

In a script, you could use this in an if statement:

#!/bin/sh

if [ "$(ls -A a/b/c)" ]; then
    echo "Not empty"
else
    echo "Empty"
fi
Jef
  • 1,128
  • 9
  • 11