-1

I have a script that uses 2 loops.
1st loop - searches for a specific file and if that file exists, other tests are performed. To avoid using a lot of CPU on a server, I have decided to use continue in a loop.
2nd loop - prints out results based on that first loop.

Script more or less looks like this:

for line in `find ./ -type f`; do

# first file test
   if [[ -f /directory/test1 ]]; then
        present=1
        continue
   fi
# second file test
   if [[ -f /directory/test2 ]]; then
        present=1
        continue
   fi
done

if [[ $present = '1' ]]; then
   echo "exists" 
else
   echo "does not exist"
fi

So basically, when the first test (first file test or second file test) is valid, continue will break up the loop and start the new iteration, so it won't reach the bottom of the script.

That will cause the second test to fail and the script will print only results with files that do not exist.

My question is: How to print out all results (exists and does not exist).

Thank you.

  • 2
    Can you post the actual script or at least all of the relevant parts? You mention two loops but only show one here and your issue as described would not happen in the provided example. You are also not doing anything with line so your loop seems ultimately pointless. – Jesse_b Jun 9 '18 at 17:46
  • 1
    What is the point of the line variable here? It looks like you're not using the output of find at all. – Kusalananda Jun 9 '18 at 18:04
3

Why not write it like this:

if [[ -f /directory/test1 || -f /directory/test2  ]]; then
    echo exists
else
    echo 'does not exist'
fi

Also you should not parse the output of find for the same reasons you shouldn't parse ls

  • Since $line is not being used, you may as well remove the loop. – Kusalananda Jun 9 '18 at 18:05
  • @Kusalananda: I'm thinking(hoping) there is more work being done within the if construct that may use line as OP indicated this wasn't the entire code. – Jesse_b Jun 9 '18 at 18:19
  • If there is, it should be converted to a loop executed by find ... -exec sh -c. – Kusalananda Jun 9 '18 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.