gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:28 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com