Question

I am trying to test the existence of .doc files in particular directory.

    if [ ! -f /home/ankur/*.doc ]
    then echo "no doc files exist."
    else echo "files exist"
    fi

Now if no doc file or single doc file exists, it works fine. but if there are multiple doc file, still it is working but throwing kind of warning "too many arguments". So how can I test the existence of multiple doc files. thanks

Was it helpful?

Solution 3

If you are only looking weather file exist or not, then I guess you should avoid that hassle:

You can simply do

#!/bin/bash

ls -l /home/ankur/*.doc &>/dev/null
if [[ $? -ne 0 ]]; then
    echo "no doc files exist."
else
  echo "files exist"
fi

One can also reduce one statement by using following if

 if ls home/ankur/*.doc &>/dev/null; then
   echo "files exist"
 else
   echo "no doc files exist."
 fi

Why to awake arrays from their sleep, if you don't want to do anything specific with them :)

OTHER TIPS

In your comments, you expand on your original question to say:

What I want is, that it checks for the files and at last produces a single result. If no doc file is there then "no doc files exist" or if one or more files are there then "doc files exist"

A lot depends on your shell. With Bash, you can use a counter to determine whether you have found any matching files. For example:

files=(/home/ankur/*.doc)
files_found=0

for file in "${files[@]}"; do
    [[ -f "$file" ]] && files_found+=1
done

if [[ $files_found == 0 ]]; then
    echo "no doc files exist"
else
    echo "files exist"
fi

The key is to use an array to store the filenames, and the loop through the test one filename at a time. The files_found variable is then checked to see if you have any matches at all. It Works for Me™.

shopt -s nullglob          # if a glob pattern matches no files, 
                           # do NOT return the pattern as a plain string,

files=( /path/to/*.doc )

if (( ${#files[@]} == 0 )); then
    echo "no doc files there"
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top