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

标签 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 S3HDR.dat 

运行文件命令显示如下:

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

但是,当我运行 ksh 脚本时,它显示以下内容:

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

关于测试文件时 Linux 意外的运算符/操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45710033/

相关文章:

VBA排名标准宏 - 否则没有如果错误

bash - 如果使用 bash 以外的任何东西,我怎么能有 term.el (ansi-term) 跟踪目录

shell - 使用反引号时如何在 KornShell 脚本中保留空格?

python - 从 bash 脚本向 python 解释器传递参数

node.js - 如何设置服务器运行 Node.js?

c# - 检查倒计时器是否为0

linux - KornShell 脚本中的 if 语句

linux - 总是无法在远程 Linux 机器上应用 SVN 补丁

c - 从多个线程读取 int 是否安全?

r - 删除特定列