0

I've written a script to check files in different directories and want this script to show me error in case a file does not exists. But It show me Both ERROR and NO ERROR due to loop. ow to adjust so that i could get only ERROR or NO ERROR in case one or more files are missing or all are existing into their directories.

files=("/my/path/to/file1.tar.gz" "/my/path/to/file2.tar.gz")

for i in "${files[@]}"
do
ls -l $i
if [ $? -ne 0 ]; then
echo "ERROR"
else
echo "NO ERROR"
fi
done

I cannot add exit, If i'll added then rest of the script below to this will stop. ls is not important. Important is to check the existence of files. It can be whatever with any way either if [ -e "/path/to/file"] etc. However ERROR is important, because in case of error or no error, i'll send an email to myself that is why its important.

Can you please explain, why you use 'set -e'?

Its not working as i want. Its printing information line by line. But i want it to store information for all and printer error if any of one is missing or no error if all exists. How is it possible to do????

3 Answers 3

2

Is the string "ERROR" important? Otherwise:

set -e
for i in "/my/path/to/file1.tar.gz" "/my/path/to/file2.tar.gz" ; do
  [ -e "$i" ]
done

Edit:

From bash manual:

          -e      Exit immediately if a simple  command  (see  SHELL  GRAMMAR
                  above)  exits  with  a non-zero status.  The shell does not
                  exit if the command that fails is part of the command  list
                  immediately following a while or until keyword, part of the
                  test in an if statement, part of a && or || list, or if the
                  command's  return value is being inverted via !.  A trap on
                  ERR, if set, is executed before the shell exits.

If you want to print, we need to be a bit more verbose:

for i in "/my/path/to/file1.tar.gz" "/my/path/to/file2.tar.gz" ; do
  [ -e "$i" ] || { echo "ERROR" ; exit 1 ; }
done
echo "NOERROR"
1

If you want to know after the loop is over, then the obvious thing would be to set a variable indicating that everything is ok. When something is not ok, you change the variable, and at the end of the loop you look in the variable to see if anything was not ok:

ok=1
for i in "${files[@]}"
do
if [ ! -e "$i" ]; then
  ok=0
fi
done
if [ $ok -eq 1 ]; then
  echo "NO ERROR"
else 
  echo "ERROR"
fi

Using [ ! -e "$i" ] will avoid printing out errors from ls though you could do

ls -l "$i" > /dev/null 2>&1

to redirect ls's output and errors to /dev/null

0

The simplest way is to remove your else statement, add an exit to your then clause, and echo "NO ERROR" after your for loop. (If you've gotten all the way through your for loop, then all the files are present.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .