0

I want to check if the argument passed while executing the script matches the prefix of a filename in my directory. I m facing binary operator expected error with my code. Does any body have any alternative approach ?

./test.sh abc
fucn_1(){
if [ -e $file_name* ] ; then 
 func_2
else 
 echo "file not found" 
 exit
fi
}

if [ $1 == abc ];
then 
file_name=`echo $1`
fucn_1
elif  [ $1 == xyz ];
then 
file_name=`echo $1`
fucn_1

while running I m passing abc as the argument such that then script can then check if the filenames starting with 'abc' is present or not in the directory. the dir has files :-

abc_1234.txt
abc_2345.txt
Nadia Alice
  • 111
  • 5
  • Possible duplicate of [Test whether a glob has any matches in Bash](https://stackoverflow.com/q/2937407/6770384). – Socowi Jul 19 '22 at 12:18
  • Also try https://www.shellcheck.net/, a great tool which would have found and [explained your mentioned problem](https://www.shellcheck.net/wiki/SC2144) as well as other problems. – Socowi Jul 19 '22 at 12:20
  • I would suggest to you, that this is a terrible idea. Instead of passing abc to the script, let the user pass abc* to the script and let the user's shell do the globbing. You're making a script that doesn't behave like unix users would expect, and you'd need a damned good reason to do that. – xpusostomos Jul 20 '22 at 07:22

1 Answers1

2

The glob $file_name* expands to a list of files. You ran [ -e abc_1234.txt abc_2345.txt ] which gives an error, since [ -e expects only one file, not two.

Try something like ...

#! /usr/bin/env bash
shopt -s nullglob
has_args() { (( "$#" > 0 )); }
if has_args "$1"*; then
  echo "$1 is a prefix of some file or dir"
else
  echo "$1 is not a prefix of any file or dir"
fi
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • Perhaps it would also be a good idea to set `dotglob` as well? – user1934428 Jul 19 '22 at 13:09
  • 1
    @user1934428 The user has to specify a *prefix*. So if they specify `.abc` then `".abc"*` will search for dot files, no matter if `dotglob` is activated or not. Only in the case of the empty prefix (i.e. `./test.sh ""`) and a directory without non-dot entries, the behavior would differ. With `dotglob` you would always get a match (at least `.` always exists) and without `dotglob` you would never get a match. But I don't think OP cares for this special case. If they did, they had to specify the expected outcome. – Socowi Jul 19 '22 at 21:43