Linux 测试文件时 operator/operand 意外
Linux unexpected operator/operand while testing for files
我在 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
的任何线索吗?有什么补救措施?
您的 if 语句不正确:您正在测试 *.dat 是否是一个文件。
问题是:*.dat
有一个 globbing 运算符 *
,它创建每个项目的列表,结尾为 .dat
。
此测试仅 运行 一次,而您有多个文件,因此多个测试 tu 运行.
尝试添加一个循环:
#! /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
中使用了以下简单的 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
的任何线索吗?有什么补救措施?
您的 if 语句不正确:您正在测试 *.dat 是否是一个文件。
问题是:*.dat
有一个 globbing 运算符 *
,它创建每个项目的列表,结尾为 .dat
。
此测试仅 运行 一次,而您有多个文件,因此多个测试 tu 运行.
尝试添加一个循环:
#! /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