2017-08-16 22 views
1

我已經在Linux中使用下面這個簡單的ksh腳本意想不到的Linux運營商/操作數,而測試的文件

#!/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和什麼是補救措施?

回答

1

您的if語句不正確:您正在測試* .dat是否爲文件。
問題是:*.dat有一個通配符運算符*,它使用.dat創建每個項目endig的列表。
此測試僅運行一次,而您有多個文件,因此多次測試運行。

嘗試增加一個循環:

#! /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