0

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?

2
  • Your example should work if you want no folders, symbolic links, etc. named *.html either.
    – Daniel Beck
    Apr 8, 2012 at 15:38
  • 1
    Why not creating a temporary directory with mktemp -d ?
    – jfg956
    Apr 8, 2012 at 17:47

3 Answers 3

1

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[@]}
1

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
1
  • 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, 2012 at 15:40
1
for i in *.html
do
  if [ -f "$i" ] 
  then
     echo "Cannot run, html files in current directory"
     exit 1
  fi
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .