【问题标题】:Linux unexpected operator/operand while testing for files测试文件时Linux意外的运算符/操作数
【发布时间】:2018-01-24 09:19:36
【问题描述】:

我有以下在 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

任何线索为什么我收到unexpected operator/operand 以及补救措施是什么?

【问题讨论】:

    标签: linux if-statement ksh


    【解决方案1】:

    您的 if 语句不正确:您正在测试 *.dat 是否为文件。
    问题是:*.dat 有一个通配符 *,它使用 .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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多