Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there are multiple files with the same name prefix

Tags:

bash

shell

how to check identical files name as prefix present or not in shell script i.e. MY_REPORT_2018_04_23_01.txt, MY_REPORT_2018_04_23_02.txt, MY_REPORT_2018_04_13_03.txt etc.

when i am trying:

if [ ! -e MY_REPORT_*.txt ] ;
 then
        echo "files not present in current directory"
        exit 1
 fi

It's working but with a warning message:

[: too many arguments

like image 374
Abhijeet Banerjee Avatar asked Dec 05 '25 04:12

Abhijeet Banerjee


1 Answers

Use an array:

#!/usr/bin/env bash
shopt -s nullglob               # make sure glob evaluates to nothing if there are no matches
files=(MY_REPORT_*.txt)         # create an array of matching files
if ((${#files[@]} == 0)); then  # check number of items in array
  echo "Files not present"
  exit 1
fi

Check this post to understand how [ ... ] works:

  • How to use double or single brackets, parentheses, curly braces

Another related post:

  • How to check if a glob matches any files
like image 127
codeforester Avatar answered Dec 07 '25 18:12

codeforester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!