Reputation: 131
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
Upvotes: 0
Views: 281
Reputation: 27215
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
Upvotes: 2