Search code examples
shellfileksh

Exit shell script if file doesn't exist


Ive got a .sql job which creates files depending on certain criteria, it writes these with a prefix of TEMP_ as we then have an adaptor that picks up the files and we dont want them picked up before writing is complete. I need to put a post job in place which renames these files, i have it set up with a number of other job but they all create the files each time they run. This job only creates the files sometimes it runs, depending on the data in the system. I need to do a check if the file exists and then exit if no file exists.

Ive found a few examples but they all seem to fail, this is where i have got to which i thought was checking if no file, if no file then exit but it fails and displays: "syntax error at line 16: `TEMP_SUBCON*.csv' unexpected"

This is what i have currently with line 16 being the first line - Above that is just comments:

    if [[ ! -f $OUT_DIR -name TEMP_SUBCON*.csv ]] ; then
    exit $?
    fi
    
    TEMP_DATA_FILE=$(find $OUT_DIR -name TEMP_SUBCON_QTY_output*.csv)
    DATA_FILE=$(basename $TEMP_DATA_FILE | cut -c6-)
    
    echo $TEMP_DATA_FILE
    echo $DATA_FILE

## Rename the file name, remove the phrase TEMP_, so that EAI can pick the file ##
mv $TEMP_DATA_FILE $OUT_DIR/$DATA_FILE

Can you help guide what ive done incorrectly?

Thanks


Solution

  • If I understand it right, you want to find the files with TEMP_ prefix in your $OUT_DIR, and then if any rename them without the prefix. Then that should do the trick

    for file in $OUT_DIR/TEMP_SUBCON_*.txt; do
        if [[ -e $file ]]; then
            mv $file $OUT_DIR/${file#*SUBCON_}
        fi
    done
    exit
    

    It will go through the directory finding each TEMP_ file and rename them without it. If there is none, it won't do anything.