IF/ELIF/ELSE语句Korn Shell

xmd2e60i  于 2023-06-30  发布在  Shell
关注(0)|答案(2)|浏览(121)

我过去有运行这些语句的经验,但没有加载。
我试图运行一个将在目录中查找,如果文件是一个.txt,然后将其发送到testdir_2,否则,如果它是一个.csv文件,然后发送到testdir_3。否则,如果是其他任何东西,则回显“错误”。
似乎正在发生的是,当代码没有找到.txt文件时,它将出错,而不是继续执行语句。
我还收到了一条“意想不到”的消息。
我可能只是错过了一些明显的东西,但我似乎不能弄清楚什么是错的。先谢谢你。

#!/bin/ksh
#set -x
#
FILEDIR=/export/home/jaqst/training/testdir_1
DIR1=/export/home/jaqst/training/testdir_2
DIR2=/export/home/jaqst/training/testdir_3
TXT=*.txt
CSV=*.csv
#
# Main processing starts here
#
echo `date +%d\ %b\ %H:%M` "Job started"
#
# Go to directory
#
cd ${FILEDIR}
if [[ $? -ne 0 ]]
   then echo `date +%d\ %b\ %H:%M` "Failed to cd into ${FILEDIR}"
   exit 9
fi
#
# Check files and move to appropriate directories
#
if [ ! -e = ${TXT} ];
   then
   mv ${TXT} /export/home/jaqst/training/testdir_2
elif [ ! -e = ${CSV} ];
   then
   mv ${CSV} /export/home/jaqst/training/testdir_3
else
   echo `date +%d\ %b\ %H:%M` "Job failed, no matching file found"
   exit 9
fi
#
echo `date +%d\ %b\ %H:%M` "Job completed"
exit 0
euoag5mw

euoag5mw1#

使用subshell,以这种方式更新代码:

if [[ -n $(ls ${TXT}) ]];
   then
   mv ${TXT} /export/home/jaqst/training/testdir_2
elif [[ -n $(ls ${CSV}) ]];
   then
   mv ${CSV} /export/home/jaqst/training/testdir_3
else
   echo `date +%d\ %b\ %H:%M` "Job failed, no matching file found"
   exit 9
fi
sqserrrh

sqserrrh2#

另一种方法:循环遍历文件并在文件名上进行模式匹配

count=0
for file in *; do
    case "$file" in
        *.txt)
            mv "$file" "$DIR1"
            ((++count))
            ;;
        *.csv)
            mv "$file" "$DIR2"
            ((++count))
            ;;
    esac
done
if [[ $count -eq 0 ]]; then
    echo `date +%d\ %b\ %H:%M` "Job failed, no matching file found"
    exit 9
fi

顺便说一下,ksh的printf可以做日期格式化,不需要调用到date:

log() {
    printf '%(%d %b %H:%M)T - %s\n' now "$*"
}
log Hello World    # => "29 Jun 08:41 - Hello World"

相关问题