Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
测试文件时Linux意外的运算符/操作数_Linux_If Statement_Ksh - Fatal编程技术网

测试文件时Linux意外的运算符/操作数

测试文件时Linux意外的运算符/操作数,linux,if-statement,ksh,Linux,If Statement,Ksh,我在Linux中使用了以下简单的ksh脚本 #!/bin/ksh set -x ### Process list of *.dat files if [ -f *.dat ] then print "about to process" else print "no file to process" fi 我的当前目录中有以下*.dat文件: S3ASBN.1708140015551.dat S3ASBN.1708140015552.dat S3ASBN.1708140015561.dat S3

我在Linux中使用了以下简单的ksh脚本

#!/bin/ksh
set -x
### Process list of *.dat files
if [ -f *.dat ]
then
print "about to process"
else
print "no file to process"
fi
我的当前目录中有以下*.dat文件:

S3ASBN.1708140015551.dat S3ASBN.1708140015552.dat S3ASBN.1708140015561.dat S3HDR.dat 
运行file命令显示以下内容:

file *.dat
S3ASBN.1708140015551.dat: ASCII text
S3ASBN.1708140015552.dat: ASCII text
S3ASBN.1708140015561.dat: ASCII text
S3HDR.dat:                ASCII text
 ./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
但是,当我运行ksh脚本时,它显示以下内容:

file *.dat
S3ASBN.1708140015551.dat: ASCII text
S3ASBN.1708140015552.dat: ASCII text
S3ASBN.1708140015561.dat: ASCII text
S3HDR.dat:                ASCII text
 ./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

有什么线索可以告诉我为什么会得到意外的运算符/操作数以及补救方法吗?

您的if语句不正确:您正在测试*.dat是否为文件。
问题是:
*.dat
有一个globbing操作符
*
,它创建每个项目的列表,并以
.dat
结尾
此测试只运行一次,而您有多个文件,因此需要运行多个测试

尝试添加循环:

#! /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
就我而言:

$> ls *.dat
53.dat  fds.dat  ko.dat  tfd.dat
产出:

$> ./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