Dr. Debasish Jana Dr. Debasish Jana - 1 year ago 102
Linux Question

Linux unexpected operator/operand while testing for files

I have the following simple ksh script used in Linux

#!/bin/ksh
set -x
### Process list of *.dat files
if [ -f *.dat ]
then
print "about to process"
else
print "no file to process"
fi


I have the following *.dat files in my current directory:

S3ASBN.1708140015551.dat S3ASBN.1708140015552.dat S3ASBN.1708140015561.dat S3HDR.dat


Running file command shows the following:

file *.dat
S3ASBN.1708140015551.dat: ASCII text
S3ASBN.1708140015552.dat: ASCII text
S3ASBN.1708140015561.dat: ASCII text
S3HDR.dat: ASCII text


However, when I run the ksh script, it shows the following:

./test
+ [ -f S3ASBN.1708140015551.dat S3ASBN.1708140015552.dat S3ASBN.1708140015561.dat S3HDR.dat ]
./test[9]: [: S3ASBN.1708140015552.dat: unexpected operator/operand
+ print no file to process
no file to process


Any clue why I am getting
unexpected operator/operand
and what's the remedy?

Answer Source

Your if statement is incorrect: you are testing if *.dat is a file.
The problem is: *.dat has a globbing operator * which creates the list of each item endig with .dat.
This test is only ran once, whereas you have multiple files so multiple tests tu run.

Try adding a loop:

#! /usr/bin/ksh
set -x
### Process list of *.dat files
for file in *.dat
do
  if [ -f $file ]
  then
    print "about to process"
  else
    print "no file to process"
  fi
done

In my case:

$> ls *.dat
53.dat  fds.dat  ko.dat  tfd.dat

Outputs:

$> ./tutu.sh 
+ [ -f 53.dat ]
+ print 'about to process'
about to process
+ [ -f fds.dat ]
+ print 'about to process'
about to process
+ [ -f ko.dat ]
+ print 'about to process'
about to process
+ [ -f tfd.dat ]
+ print 'about to process'
about to process
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download