Nested if in KSH

Trying to clean up the last little thing in this script which is that the mv always performs no matter whether it is needed or not. It doesn't cause any bugs just prints an unsightly "can't mv source and dest are the same". Obviously I want to get rid of it but having issues getting the nested if to work and google has not been helpful this time.

Below is one of the many variations of nested ifs i have tried from various examples.

thanks in advance

 for i in `ls -pcr | grep -v [\/] `
 do
                 echo "PRE; $PREMID_DT_TM and Post; $POSTMID_DT_TM"
         if [ -e ${i} ]
         then
             echo "Processing file ${i}"      
             TEMP=$(echo "${i}" | sed -e "s/$PREMID_DT_TM/$POSTMID_DT_TM/")
           if     [[ ${i} -eq ${TEMP}]]
           then
           #
           else
               mv ${i} ${TEMP}
           fi
         fi
 done
 
  1. You are using a numeric comparision operator (-eq) to compare strings.
  2. Why don't you test for inequality instead of equality?
  3. You are missing whitespace between your test arguments and the square brackets

Then your test becomes

if [[ "${i}" != "${TEMP}" ]]
then
   mv ${i} ${TEMP}
fi

There is probably a more efficient way of generating your file list but that's not what your main issue is.

1 Like

I was unable to find a better way to get ls to list by modified times and not include directories. I tried various solutions but the directories were always included.

I will try your suggestion for the if and reply thanks.

---------- Post updated at 11:58 AM ---------- Previous update was at 11:46 AM ----------

for i in `ls -pcr | grep -v [\/] `
do
                echo "PRE; $PREMID_DT_TM and Post; $POSTMID_DT_TM"
        if [ -e ${i} ]
        then
            echo "Processing file ${i}"      
            TEMP=$(echo "${i}" | sed -e "s/$PREMID_DT_TM/$POSTMID_DT_TM/")
          if [[ "${i}" != "${TEMP}" ]]
                    then
                   mv ${i} ${TEMP}
                    fi
        fi
done

it's saying the then is unexpected.

Also i think I tried testing for inequality first i just kept trying different examples on google trying to get it to work.

I'm not sure why it's saying "then" is unexpected. Maybe because you forgot to quote ${i} -- if it's blank for some reason, that becomes [ -e ] instead of [ -e "" ] which is syntactically wrong.

The continue operator is nice for avoiding confusing levels of nesting. It skips the current item and goes back to the top of the loop (or exits if there's no more items). How about:

for i in ...
do
        [ -f "${i}" ] || continue

        echo "processing "${i}"
        ...
done
1 Like

putting quotes around it fixed it. Thanks both of you!