I have a script with many commands. Like

mv new /root/
mv old /root/ 
mv foo /code
#many other commands

If the file 'new' is not found bash will give an error message:foo: No such file or directory

I can suppress the error message by redirecting all output from stderr to /dev/null

mv foo /code 2>1 /dev/null

Is there a way to simply do it without modifying whole script? Is there a way in which to suppress all the error message in a script?

  • 1
    You can redirect all of stderr when running the script, i.e. ./myscript.sh 2 > /dev/null – ernie Nov 15 '13 at 17:24
  • Question: Do you mean the normal bourne shell (as in your /bin/sh example) or bash (which you tagged it with). – Hennes Nov 15 '13 at 17:33
  • yes normal shell – The KingMaker Nov 15 '13 at 17:35
  • 1
    The question is why you're writing a script that you expect to throw errors on files that aren't found. You should check if the source file(s) and the target(s) exist(s) before moving it/them somewhere. The proper way to get rid of an error message is to prevent the error from happening in the first place. – slhck Nov 15 '13 at 17:35

You can suppress all messages in the script by starting the script like this:
yourcommand &>filename. E.g. ./myscript &> /dev/null

Or you could use your_script 2> /dev/null

The last will redirect all output from stderr to the bitbucket with no need to append that to every command. Since this removes all the errors from the visible output this will make the script very hard to debug. You should check the return value of each command to see if an error occurred and optionally abort.

You can do the latter with $?.


#!/usr/bin/env bash
mv new /root/
if [[ $? -ne 0 ]]; then
   #ignore error since it is not important, or
   # echo "YIPES! CRITICAL FAILURE. Aborting whole script!
   exit 1
Next command here

Etc etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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