Search code examples
shellif-statementksh

IF/ELIF/ELSE Statement Korn Shell


Ive had experiences running these statements in the past but not loads.

Im trying to run one that will look in the directory and if the file is a .txt then send it to testdir_2 else if it is a .csv file then send to testdir_3. Else if it is anything else echo "error".

What seems to be happening is when the code doesn't find the .txt file it will error out instead of continuing with the statement.

Im also getting a "else unexpected" message.

I may just be missing something obvious but I cannot seem to work out what is wrong. Thank you in advance.

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

Solution

  • A different approach: loop over the files and pattern match on the filename

    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
    

    By the way, ksh's printf can do date formatting, no need to call out to date:

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