How to Collect Logs from My Script (Maybe Using File Descriptors)

Below is a part of my script . Whenever the script executes ‘ls -ld $dir1’ it throws a msg while script is in execution. Could someone let me know to avoid that message and could be collected separately via stderr or logs by using any of the filedescriptor.

echo -e "\nChecking if the directory $dir1 already exists\n"                                                     

ls -ld $dir1  

  

if [ $? -eq 0 ]                                                                                                  

then                                                                                                             

echo -e "\nDirectory exists!!! Checking to verify if the same directory exists in /etc/fstab\n"                  

else                                                                                                             

echo -e "\nCreating directory $dir1\n"; mkdir $dir1                                                              

echo -e "$dir1\t$ip1($per1,sync,$rperm2,no_subtree_check)" >> share                                              

fi                                                                                                               

done

simply don’t use ls inside scripts!

if test -d "$dir1"
then
   :...
else
   :...
fi

I’m not sure of your issue (i think your testing isn’t good use -d) but this kind of thing to me should be tested on the start of the script. I see little people doing this but I use functions and I just do all most my checking before the script gets into doing it’s work, it seems the most logical thing to do.

# example using BASH4+
MY_DIR="/tmp"
.. ... ...
function check_initial_configs()  {
    # check for directories, commands, root (if needed) etc. in this function 
    [[ -d "$MY_DIR" ]] && { echo "$MY_DIR found .."; } || { echo "Fatal Error:  $MY_DIR, not found! "; exit 7; }
}

check_initial_configs
perform_system_backup
... ... ...