1

I'm new to shell scripting and writing a script with multiple rm commands. the script has to remove files in some directories. I want to capture the exit status for each command and return the exit status if something fails and proceed with the next command. Can someone help me to correct my script.

    #!/bin/bash
    PATH1=mydir/folder/
    PATH2=mydir/newfolder/

    HOST= hostname | grep -o "[0-9]*" | head -1
   case "$HOST" in
   01)echo "Removing files in server 1.."
    find $PATH1/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -name "*.out*" \) -exec rm -f {} \;
    find $PATH1/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -name "*.out*" \) -exec rm -f {} \;
    RETVAL=$?
    ;;
   02)echo "Remove logfiles in server 02"
   find $PATH2/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -   name "*.out*" \) -exec rm -f {} \;
   find $PATH2/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -name "*.out*" \) -exec rm -f {} \;
   RETVAL=$?
   ;;
   *)
   echo "Removal of log files is complete"
   esac
Linux_Bee
  • 109
  • 3
    Please copy and paste your actual script. Don't just retype it. There are several errors in this script that show it's clearly never been run, and there's little point trying to correct only an approximation to reality. – Chris Davies Oct 31 '16 at 18:13

1 Answers1

-2

an echo $? should return the status of the previous command. so you might want to use

if [ ! $? -eq 0 ]; then
    echo "command failed"
else
    echo "command success"
fi
bscullion
  • 101
  • An exit on error can have different values. It is better to check for EX_OK which should always be 0. Also, there is no need for an echo, if [[ $? == 0 ]] is enough. –  Oct 31 '16 at 19:08