I'm trying to use the following condition to detect *.tgz archives in a directory:
if [ -e ${INPUT_DIRECTORY}*tgz ]
While this condition works great when there is only one file, it's giving me an expected binary operator error on the 'if' line of my script, when there is more than one *.tgz file in the directory.
What am I missing ?
You can just ls it, then check the exit code of ls. If it's 0 then the file exist, otherwise it doesn't.
$ ls wfh.sh
wfh.sh
$ echo $?
0
$ ls a
ls: cannot access 'a': No such file or directory
$ echo $?
2
In your case, you can write:
ls ${INPUT_DIRECTORY}*.tgz > /dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "exist!"
else
echo "not!"
fi
Also, you should change your globbing to ${INPUT_DIRECTORY}*.tgz instead of ${INPUT_DIRECTORY}*tgz since it may unintentionally match something like filletgz
For more readable script, you can also write:
if ls ${INPUT_DIRECTORY}*.tgz > /dev/null 2>&1 ; then
echo "exist!"
else
echo "not!"
fi
Here’s a suggestion for a test, in pure shell:
for i in "$input_dir"/*.tgz "$input_dir"/.*.tgz; do
test -e "$i" && break
done
This returns success or failure, depending on if .tgz files exist. You can obviously remove the second pattern if you want to ignore hidden files.
As a function/example:
suffix_exists ()
{
for i in "${2:-.}"/*"$1" "${2:-.}"/.*"$1"; do
test -e "$i" && return 0
done
}
if suffix_exists .tgz "$input_dir"; then
echo "$input_dir contains .tgz archives"
else
echo "$input_dir does not contain .tgz archives"
fi
It uses the current directory if none is provided.
As mentioned in another answer, you might be approaching your task in the wrong way (perhaps post your objective). Instead of detecting .tgz archives in the directory, you could run a command on any archives that do exist, using find. For example extracting them:
find "$input_dir" -mindepth 1 -maxdepth 1 \
-type f -name '*.tgz' -exec tar xf {} \;
Or moving them somewhere:
find "$input_dir" -mindepth 1 -maxdepth 1 \
-type f -name '*.tgz' -exec mv -i {} /my/archives \;