Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Detect multiple tgz files in a directory with shell script

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 ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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 \;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!