1

I'm cleaning the output of my scripts. For example:

rm -f ./file

No such file or directory

I want to implement some error checking for this command, equivalent to a try/catch statement. In other words, I want to catch the error if the command fails.

2
  • 5
    rm -f blahblahblah does not print an error message on my system. Does it on yours? What system? Commented Jan 8, 2015 at 4:43
  • just a hint: search for set -e, trap... Commented Jan 8, 2015 at 6:38

3 Answers 3

4

Python:

try:
    os.remove('./file')
    champagne_for_everybody
except:
    throw_myself_in_the_river

Shell:

if rm ./file
then
    champagne_for_everybody
else
    throw_myself_in_the_river
fi

Notes:

  • Don't use -f - POSIX rm ignores missing files when using -f.
  • Don't use shell if you can avoid it. Python and other modern languages have much more sophisticated error handling built in.
Sign up to request clarification or add additional context in comments.

Comments

3

Why not use a simple script?

file=$1
if [ ! -f $file ]; then
    echo "File not found!"
else 
    rm -f $file
fi

When you run it, the script will tell you whether a given file does not exist.

You can also redirect to both stderr and stdout by using 2>&1 after the echo command. You may also add an exit 1 at the end of the if statement, because an exit status of 1 generally indicates that the command was not executed successfully.

This will not work in the exact way as you intend it to, but in bash this is the closest way of detecting errors.

Comments

2

use set -e or you can achive same behaviour using && or ||

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.