Shell script to check for the presence of one or more files with a specific extension?
If you don't want recursion, you can do
export DIR=/home/Savio/Dsktop/check
if ls ${DIR}/*.txt &>/dev/null && ls ${DIR}/*.csv &>/dev/null
then
echo "Found."
else
echo "Not found."
fi
Or, in perl
:
perl -e '
$DIR="/home/Savio/Dsktop/check";
@a= glob "${DIR}/*.txt";
@b= glob "${DIR}/*.csv";
print @a && @b ? "Found.\n" : "Not found.\n"
'
If you do want recursion, the solution proposed in the other answers will work. You can make it go faster by making find
stop after the first match it finds:
export DIR=/home/Savio/Dsktop/check
CSV=$(find "$DIR" -name *.csv|head -n1)
TXT=$(find "$DIR" -name *.txt|head -n1)
[ ! -z "$CSV" ] && [ ! -z "$TXT" ] && echo Found || echo Not found
References
- Stephane Chazelas' great answer to How to stop the find command after first match?
The wildcard in file1
is never expanded because it's always in quotes.
In bash, one way is to set the nullglob
option so that a wildcard that matches no file expands to an empty list.
#!/bin/bash
shopt -s nullglob
csv_files=(/home/Savio/Dsktop/check/*.csv)
txt_files=(/home/Savio/check/*.txt)
if ((${#csv_files[@]} && ${#txt_files[@]}))
then
echo " found."
else
echo "not found."
fi
If you want to match dot files as well, set the dotglob
option.
With only a POSIX shell, you need to cope with the pattern remaining unchanged if there is no match.
matches_exist () {
[ $# -gt 1 ] || [ -e "$1" ]
}
if matches_exist /home/Savio/Dsktop/check/*.csv &&
matches_exist /home/Savio/check/*.txt; then
echo " found."
else
echo "not found."
fi
Note that it looks for files regardless of their type (regular, directory, symlink, device, pipe...) while your [[ -f file ]]
checks whether the file exists and is a regular file or symlink to regular file only (would exclude directories, devices...).