Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a script which will download html files into current directory.
Then it'll generate a report based on these html files.
At last, it'll delete all these html files.
So, when I run this script, I want to make sure there is no html files in current dir.

This is what I got:

if ls *.html >/dev/null 2>&1; then
    echo 'clear HTML files first'
    exit
fi

Is there any easy way to check?

share|improve this question
    
Your example should work if you want no folders, symbolic links, etc. named *.html either. –  Daniel Beck Apr 8 '12 at 15:38
1  
Why not creating a temporary directory with mktemp -d ? –  jfgagne Apr 8 '12 at 17:47
add comment

3 Answers

up vote 1 down vote accepted

Using the failglob option; checks for any matches:

if (shopt -s failglob; true *.html) 2>/dev/null; then
    echo "Found files"
fi

Using nullglob and arrays; counts the files:

numfiles=$( shopt -s nullglob; files=(*.html); echo ${#files[@]} )

if (( numfiles > 0 )); then
    echo "Have $numfiles HTML files"
else
    echo "No files"
fi

Another way, without using nullglob or discarding $files:

files=(*.html)
if [[ -e ${files[0]} ]]; then
    numfiles=${#files[@]}
    echo "$numfiles files found"
fi

Using nullglob for the entire script – might be okay in some cases, bad in others:

#!/usr/bin/env bash
shopt -s nullglob

...

files=(*.html)
numfiles=${#files[@]}
share|improve this answer
add comment
for i in *.html
do
  if [ -f "$i" ] 
  then
     echo "Cannot run, html files in current directory"
     exit 1
  fi
done
share|improve this answer
add comment

Count the number of HTML files (not folders, symbolic links, etc.) in the current directory, and, if greater than zero, abort:

if [[ $( find . -maxdepth 1 -type f -name "*.html" | wc -l ) -gt 0 ]] ; then
    echo "Oh no, there are HTML files!" >&2
    exit 1
fi
share|improve this answer
    
While newlines in file names will break the counter, they only increase it. Any match will increase the counter beyond 0. –  Daniel Beck Apr 8 '12 at 15:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.