0

I am trying to use the if condition in shell script to check whether some files (starting with similar names) exist or not in the working directory. My problem is I have more than one file viz. "A1.txt", "A2.txt", "A3.txt" etc in my working directory. Now my question is, is there a way to check for files with the part of the string of the file name. So if the script finds at least one file with name starting with "A" then it prints that file found of there is no file with file name starting with "A" it does not print so. My attempt is the following :

if [ -f "A*.txt" ];
then
echo "Files exist."
else
echo "Files do not exist"
fi

But it does not work and returns "too many arguments". Is there a way out?

BabaYaga
  • 457
  • 5
  • 20

2 Answers2

2

In BASH you can use:

( shopt -s nullglob; set -- A*.txt; (( $# > 0 )) ) &&
    echo "Files exist." || echo "Files don't exist"

When it find a matching file it will exit with 0 and prints:

Files exist.

when it doesn't find any matching file/directory with the given glob pattern it will exit with 1 and print:

Files don't exist

Explanation:

  • shopt -s nullglob causes shell to fail silently if no matching file is there for the glob
  • set -- assigns given arguments to the positional parameters $1,$2,$3 etc.
  • $# is number of positional arguments. It will be set to greater than zero if any matching file is found
  • ((...)) is used for arithmetic evaluation in bash
  • (..) creates a sub-shell for the above commands so that current shell's env is not affected
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    This is currently the only acceptable answer, though it should probably expand on why the correct solution is rather roundabout. – tripleee Mar 01 '16 at 11:09
1

this could be one way:

#!/bin/bash

check=`ls A*.txt 2> /dev/null`

if [ ! -z "${check}" ];
then
echo "Files exist."
else
echo "Files do not exist"
fi

then you can inprove the check variable with a regex if you need i.e. to get only the file with number you can do something like check=ls A[1-9]*.txt

Regards

Claudio

ClaudioM
  • 1,418
  • 2
  • 16
  • 42