You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Korn Shell IF/ELIF/ELSE语句执行异常及语法错误求助

Korn Shell脚本问题排查与修复

问题描述

有少量Korn Shell条件语句使用经验,编写脚本实现以下功能:

  • 遍历指定目录,将.txt文件移至testdir_2
  • 将.csv文件移至testdir_3
  • 无匹配文件时输出错误信息

运行时遇到两个问题:

  1. 未找到.txt文件时直接报错,不执行后续分支
  2. 出现else unexpected语法提示

原脚本代码:

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

错误原因分析

  1. 语法错误触发else unexpected:[ ! -e = ${TXT} ]中的=是多余的,-e选项仅需接收一个路径参数,多余的=会被当作无效参数,导致条件判断语法错误,进而引发else unexpected提示。
  2. 逻辑与通配符问题:
    • 原条件判断写反:! -e是判断文件不存在,导致只有.txt文件不存在时才执行移动操作,完全违背需求。
    • 无匹配文件时通配符被当作字符串:当*.txt未匹配到任何文件,Ksh默认会将*.txt当作普通文件名处理,此时mv命令会尝试移动不存在的*.txt文件,直接报错退出,无法执行后续分支。

修正后的脚本

#!/bin/ksh
#set -x
#
FILEDIR=/export/home/jaqst/training/testdir_1
DIR_TXT=/export/home/jaqst/training/testdir_2
DIR_CSV=/export/home/jaqst/training/testdir_3
#
# Main processing starts here
#
echo "$(date +'%d %b %H:%M') Job started"
#
# Go to directory
#
cd "${FILEDIR}" || {
    echo "$(date +'%d %b %H:%M') Failed to cd into ${FILEDIR}"
    exit 9
}
#
# Check and move files
#
txt_found=0
csv_found=0

# Handle .txt files
for file in *.txt; do
    if [ -f "$file" ]; then
        mv "$file" "${DIR_TXT}"
        txt_found=1
    fi
done

# Handle .csv files
for file in *.csv; do
    if [ -f "$file" ]; then
        mv "$file" "${DIR_CSV}"
        csv_found=1
    fi
done

# Check if any files were processed
if [ $txt_found -eq 0 ] && [ $csv_found -eq 0 ]; then
    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

关键修正点

  • 修复语法错误:移除条件判断中多余的=,调整逻辑为判断文件存在而非不存在。
  • 解决通配符问题:用for循环遍历通配符,配合-f判断是否为真实文件,避免无匹配时将通配符字符串当作文件名处理。
  • 优化逻辑:分别处理两种类型文件,记录是否有文件被处理,最后统一判断无匹配的情况,确保两种文件都能被处理,而非互斥执行。
  • 代码可读性优化:用$(date ...)替代反引号(支持嵌套且更易读),用cd ... || { ... }简化错误处理,变量命名更清晰(DIR_TXT/DIR_CSV)。

内容的提问来源于stack exchange,提问作者STAKD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:27:25