1

This question already has an answer here:

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

marked as duplicate by Christopher, HalosGhost, thrig, Jeff Schaller, Satō Katsura Oct 31 '16 at 20:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – roaima Oct 31 '16 at 18:13
-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
  • 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. – maulinglawns Oct 31 '16 at 19:08

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