Bash disable error output

Do you want to suppress or hide all the output of a Linux Bash Shell Script ? Do you want to redirect all the output to /dev/null ? Are you looking to silence

Do you want to suppress or hide all the output of a Linux Bash Shell Script ? Do you want to redirect all the output to /dev/null ? Are you looking to silence all the output of a Linux Bash Shell Script ? Are you looking to redirect all the error to output ? Do you want to know how to redirect all the output of Bash Shell script to a file ? If yes then you have reached the correct place.

Here I am going to explain all the different methods that can be used to achieve these tasks. You can use all the below explained methods to not just suppress or hide the output of Linux bash shell script from command line but from the crontab as well. So stay focused!!!

How to Suppress or Hide all the Output of a Linux Bash Shell Script

Also Read: 25 Practical and Useful rpm command examples in Linux{cheatsheet}

Method 1: How to Suppress or Hide all the output of a Linux bash shell script

If you are looking to suppress or hide all the output of a bash shell script from Linux command line as well as from the crontab then you can simply redirect all the output to a file known as /dev/null. This file is known as Black Hole which will engulf everything you give without complaining. Hence this is the best place to redirect all the output. In this method we are sending example.sh script output to /dev/null.

[root@localhost ~]# ./example.sh > /dev/null

Method 2: How to Suppress or Hide all the Error messages from a Linux Shell Script 

Using above method you can easily suppress all the output of a Bash Shell Script but what about the script error messages if there is any ? Error messages will not suppressed by above method. For that you need to use another method where you first need to redirect all the error messages to the output and then redirect all the output to /dev/null using earlier explained method. In this method we are sending example.sh script output and its error messages to /dev/null. 2>&1 simply means send the error to the same place output is being sent.

[root@localhost ~]# ./example.sh > /dev/null 2>&1

Method 3: How to Redirect All the output of a Bash Shell Script to a File

If you think output of the Bash Script will be needed later then instead of redirecting all the output of the script to /dev/null you can redirect and save it in a file for later use. You can check more on Bash Guide for Beginners. In this method we are redirecting example.sh script output to file.log.

[root@localhost ~]# ./example.sh > file.log

Method 4: How to Redirect All the error messages of Bash Shell Script to a File

Similarly for the error messages also you can redirect all the error messages to a file instead of redirecting it to /dev/null from where messages cannot be retrieved back. This is really important in the production or critical cases where you are running a bash shell script in crontab and suddenly some error occurred and now you need to debug that error. In those scenarios saving error messages in a file will be much helpful. In this method we are redirecting example.sh script output and its error messages to file.log.

[root@localhost ~]# ./example.sh > file.log 2>&1

Popular Recommendations:-

How to Defragment an XFS Filesystem in Linux(5 Simple and Effective Steps)

How to Install jq(JSON Processor) on RHEL/CentOS 7/8 

How to Install Arpwatch tool on RHEL/CentOS 7/8(Simple and Effective Steps)

How to Install and Configure Squid Proxy Server on RHEL/CentOS 7/8

Python3: ModuleNotFoundError: No Module Named «prettytable» in Linux 

How to List all the Installed Python Modules in Linux{2 Easy Methods}

Solved: ModuleNotFoundError: No Module Named «requests» in Python 3

How to Install and Enable EPEL Repository on RHEL/CentOS 7/8{Simple and Easy Steps}

  1. Introduction to Shell and Scripting
  2. Suppress Output of Command in Bash Script

Bash Suppress Output

This article will explain methods to suppress the output of commands using Bash. Moreover, we will also look into redirecting the output to a file for later use.

Introduction to Shell and Scripting

Shell is a program that runs a command line interface in Linux. In Linux, all users can use many different shells.

Commonly, a default GNU’s Bourne-Again Shell (Bash) is used in many Linux distributions.

A file containing a series of commands is called a script. This file is read and executed using the Bash program.

For example, assume a file with the name First.sh has contents as follows:

#!/bin/bash
echo "Hello"
echo "World"

In the above example, First.sh is a script file that contains two echo commands that will display Hello World on the terminal when the script executes. The first line, #!/bin/bash, flags the interpreter’s location to be used for running the script.

We can execute the Bash script on the Linux terminal in two different ways.

Output:

Output:

Suppress Output of Command in Bash Script

We can suppress the output of any commands written in a Bash script during the execution of a Bash script. We can redirect the output to a null device.

For example, if we want to suppress the output of the First.sh script, we can use the following command.

This command suppresses the output of the First.sh script and does not display anything on the terminal. However, if the First.sh script contains any error, it will still be displayed on the terminal.

Consider the following command in the First.sh script.

#!/bin/bash
echo "Hello
echo "World"

In the script, " is missing in the first echo command. The output of the following script run using ./First.sh is as follows:

./First.sh: line 3: unexpected EOF while looking for matching `"'
./First.sh: line 4: syntax error: unexpected end of file

If we run this script using the command ./First.sh > /dev/null will show the same output.

./First.sh: line 3: unexpected EOF while looking for matching `"'
./First.sh: line 4: syntax error: unexpected end of file

Suppress Errors of a Bash Script

If any Bash script contains an error, the ./scriptname > dev/null command does not suppress the error and displays the error on the terminal, as discussed above.

We can suppress the error from the terminal, also. The following commands can suppress the output and the error from the terminal while executing the First.sh Bash script.

./First.sh &>/dev/null
./First.sh >/dev/null 2>&1
./First.sh >/dev/null 2>/dev/null

The first command ./First.sh &>/dev/null maybe not work for all Linux shells.

Record or Store the Output of Bash Scripts

The output is suppressed when we use the /dev/null during the execution of the Bash script. However, we can store or record the output in customized files.

Consider the following First.sh script.

#!/bin/bash
echo "Hello"
echo "World"

We can use the following command to run the First.sh script to store or record the Bash output.

./First.sh > outputfile.out

When we execute the above command, it will not show anything on the terminal; however, a new file with the name outputfile.out is created (if not exists already), and the contents of the file are:

If the outputfile.out already exists, the existing content is varnished, and the script’s new output is stored in the file.

Hiding the output of a shell command usually involves redirecting stderr and stdout. Is there any builtin facility or command which by default hides the output but on error dumps all the accumulated output? I would like to run this as a wrapper for remote ssh commands. Now I have them using redirection but I don’t get a clue as to what made them fail, and they are just too verbose.

EDIT: In the end I created the following template based on the answer by @Belmin which I tweaked a little bit to accumulate all the previous commands from the script, use the current process identifier, automatically remove the log, and add a failure red error message when something goes wrong. In this template the initial silent wrappers will succeed, then fail the third command because the directory already exists:

#!/bin/sh

set -e

SILENT_LOG=/tmp/silent_log_$$.txt
trap "/bin/rm -f $SILENT_LOG" EXIT

function report_and_exit {
    cat "${SILENT_LOG}";
    echo "33[91mError running command.33[39m"
    exit 1;
}

function silent {
    $* 2>>"${SILENT_LOG}" >> "${SILENT_LOG}" || report_and_exit;
}

silent mkdir -v pepe
silent mkdir -v pepe2
silent mkdir -v pepe
silent mkdir -v pepe2

Community's user avatar

asked Jun 25, 2014 at 16:18

Grzegorz Adam Hankiewicz's user avatar

4

I’d setup a bash function like this:

function suppress
{
   /bin/rm --force /tmp/suppress.out 2> /dev/null; 
   ${1+"$@"} > /tmp/suppress.out 2>&1 || 
   cat /tmp/suppress.out; 
   bin/rm /tmp/suppress.out;
}

Then, you could just run the command:

suppress foo -a bar

mc0e's user avatar

mc0e

5,82617 silver badges31 bronze badges

answered Jun 25, 2014 at 17:34

Belmin Fernandez's user avatar

Belmin FernandezBelmin Fernandez

10.7k26 gold badges84 silver badges147 bronze badges

5

It should be easy enough to write a script for this purpose.

Something like this completely untested script.

OUTPUT=`tempfile`
program_we_want_to_capture &2>1 > $OUTPUT
[ $? -ne 0 ]; then
    cat $OUTPUT
    exit 1
fi
rm $OUTPUT

On the other hand for commands I run as part of a script I usually want something better than simply print all the output. I often limit what I see to the unknown. Here is a script I adapted from something I read over a decade ago.

#!/bin/bash

the_command 2>&1 | awk '
BEGIN 
{
  # Initialize our error-detection flag.
  ErrorDetected = 0
}
# Following are regex that will simply skip all lines
# which are good and we never want to see
/ Added UserList source/ || 
/ Added User/ || 
/ init domainlist / || 
/ init iplist / || 
/ init urllist / || 
/ loading dbfile / || 
/^$/ {next} # Uninteresting message.  Skip it.

# Following are lines that we good and we always want to see
/ INFO: ready for requests / 
{
  print "  " $0 # Expected message we want to see.
  next
}

# any remaining lines are unexpected, and probably error messages.  These will be printed out and highlighted.
{
  print "->" $0 # Unexpected message.  Print it
  ErrorDetected=1
}

END 
{
  if (ErrorDetected == 1) {
    print "Unexpected messages ("->") detected in execution."
    exit 2
  }
}
'
exit $?

answered Jun 25, 2014 at 17:11

Zoredache's user avatar

ZoredacheZoredache

130k40 gold badges271 silver badges414 bronze badges

I don’t think there is a clean way of doing this, the only thing I can think of is

  • Capture the output of the command.
  • Check the return value of the command and if it failed
    • display the captured output.

Implementing this might though be a interesting project but perhaps beyond Q&A.

answered Jun 25, 2014 at 16:54

user9517's user avatar

2

Don’t reinvent the wheel on this one. It’s a common problem, notably with cron jobs, which is why cronic/chronic were created. You can likely install one from your package manager, and the usage is as simple as this:

cronic noisy_command --param paramval

It will suppress all output unless the noisy command produces non-trace error output or has a non-zero exit status.

answered Jun 11, 2021 at 2:24

Walf's user avatar

WalfWalf

3221 gold badge3 silver badges16 bronze badges

3

Try so:

out=`command args...` || echo $out

answered Jun 26, 2014 at 9:06

user2743554's user avatar

user2743554user2743554

3973 silver badges13 bronze badges

3

going short with something like tehcommand &>/tmp/$$ || cat /tmp/$$

depends how much usability/typing you want/need. (e.g. using it as a pipe or passing the command by argument)

@zoredache short script is basically a proto-wrapper for this, which would give more robustness, handle concurrency, etc

answered Jun 25, 2014 at 17:24

rogerovo's user avatar

rogerovorogerovo

2642 silver badges7 bronze badges

I’m trying to show the number of lines, words and characters of all configuration files in /etc/*conf (with command wc).

How can I modify the command (or commandline) to not view the error messages?

quack quixote's user avatar

quack quixote

41.7k14 gold badges104 silver badges130 bronze badges

asked Mar 25, 2010 at 22:26

pedro's user avatar

1

wc /etc/*conf 2>/dev/null

answered Mar 25, 2010 at 23:33

Dennis Williamson's user avatar

Dennis WilliamsonDennis Williamson

104k19 gold badges164 silver badges187 bronze badges

i don’t have access to a shell right now, but you can try something like

cat /etc/*.conf 2> /dev/null | wc -l

That should redirect all the errors and leave the output to be passed to wc

answered Mar 25, 2010 at 22:39

Roy Rico's user avatar

Roy RicoRoy Rico

5,7287 gold badges42 silver badges57 bronze badges

1

Usually just redirect the standard output to /dev/null to ignore the output, but this is not good practice when writing shell scripts

Try use -q instead to run the shell in quite mode, which will produce less output.

This might not be relevant to the question, but just FYI.

answered May 1, 2013 at 7:10

imcoddy's user avatar

imcoddyimcoddy

2711 gold badge2 silver badges5 bronze badges

Bash, or the Bourne-Again Shell, is a powerful command-line interface (CLI) that is commonly used in Linux and Unix systems. When working with Bash, it is important to understand how to handle errors that may occur during the execution of commands. In this article, we will discuss various ways to understand and ignore errors in Bash. Bash scripting is a powerful tool for automating and simplifying various tasks in Linux and Unix systems. However, errors can occur during the execution of commands and can cause scripts to fail. In this article, we will explore the various ways to understand and handle errors in Bash. We will look at ways to check the exit status code and error messages of commands, as well as techniques for ignoring errors when necessary. By understanding and properly handling errors, you can ensure that your Bash scripts run smoothly and achieve the desired outcome.

Step-by-step approach for understanding and ignoring errors in Bash:

Step 1: Understand how errors are generated in Bash.

  • When a command is executed, it returns an exit status code.
  • A successful command will have an exit status of 0, while a failed command will have a non-zero exit status.
  • Error messages are generated when a command returns a non-zero exit status code.

Step 2: Check the exit status code of a command.

  • To check the exit status code of a command, you can use the $? variable, which holds the exit status of the last executed command.
  • For example, after executing the command ls non_existent_directory, you can check the exit status code by running echo $? The output
  • will be non-zero (e.g., 2) indicating that the command failed.

Step 3: Check the error message of a command.

  • To check the error message of a command, you can redirect the standard error output (stderr) to a file or to the standard output (stdout) using the 2> operator.
  • For example, you can redirect the stderr of the command ls non_existent_directory to a file by running ls non_existent_directory 2> error.log. Then you can view the error message by running cat error.log.

Step 4: Use the set -e command.

  • The set -e command causes the script to exit immediately if any command exits with a non-zero status. This can be useful for detecting and handling errors early on in a script.
  • For example, if you run set -e followed by ls non_existent_directory, the script will exit immediately with an error message. 

Step 5: Ignore errors when necessary.

  • To ignore errors, you can use the command || true construct. This construct allows you to execute a command, and if it returns a non-zero exit status, the command following the || operator (in this case, true) will be executed instead.
  • For example, you can run rm non_existent_file || true to remove a file that does not exist without exiting with an error.
  • Another way to ignore errors is to use the command 2> /dev/null construct, which redirects the standard error output (stderr) of a command to the null device, effectively ignoring any error messages.
  • Additionally, you can use the command 2>&1 >/dev/null construct to ignore both standard error and standard output.
  • You can also use the command || : construct which allows you to execute a command and if it returns a non-zero exit status, the command following the || operator (in this case, 🙂 will be executed instead. The: command is a no-op command that does nothing, effectively ignoring the error.

Practical Explanation for Understanding Errors

First, let’s examine how errors are generated in Bash. When a command is executed, it returns an exit status code. This code indicates whether the command was successful (exit status 0) or not (non-zero exit status). For example, the following command attempts to list the files in a directory that does not exist:

$ ls non_existent_directory
ls: cannot access 'non_existent_directory': No such file or directory

As you can see, the command generated an error message and returned a non-zero exit status code. To check the exit status code of a command, you can use the $? variable, which holds the exit status of the last executed command.

$ echo $?
2

In addition to the exit status code, you can also check the standard error output (stderr) of a command to understand errors. This can be done by redirecting the stderr to a file or to the standard output (stdout) using the 2> operator.

For example, the following script will redirect the stderr of a command to a file:

$ ls non_existent_directory 2> error.log
$ cat error.log
ls: cannot access 'non_existent_directory': No such file or directory

You can also redirect the stderr to the stdout using the 2>&1 operator, which allows you to see the error message along with the standard output of the command.

$ ls non_existent_directory 2>&1
ls: cannot access 'non_existent_directory': No such file or directory

Another useful tool for understanding errors is the set -e command, which causes the script to exit immediately if any command exits with a non-zero status. This can be useful for detecting and handling errors early on in a script.

$ set -e
$ ls non_existent_directory
# as soon as you hit enter this will exit shell and will close the terminal.

After this command script will exit from the shell if the exit code is nonzero.

Practical Explanation for Ignoring Errors

While it is important to handle errors in Bash scripts, there may be certain situations where you want to ignore errors and continue running the script. In this section, we will discuss different methods for ignoring errors in Bash and provide examples of how to implement them.

Heredoc

Heredoc is a feature in Bash that allows you to specify a string or command without having to escape special characters. This can be useful when you want to ignore errors that may occur while executing a command. The following example demonstrates how to use Heredoc to ignore errors.

#!/bin/bash

# Example of ignoring errors using Heredoc

# The `command` will fail but it will not stop execution
cat <<EOF | while read line; do
  echo $line
done
command that will fail
EOF

# Rest of the script

In this example, the command that is inside the Heredoc will fail, but the script will not stop execution. This is because the output of the command is piped to the while loop, which reads the output and ignores the error.

Pipefail

The pipe fails option in Bash can be used to change the behavior of pipelines so that the exit status of the pipeline is the value of the last (rightmost) command to exit with a non-zero status or zero if all commands exit successfully. This can be useful when you want to ignore errors that may occur while executing multiple commands in a pipeline. The following example demonstrates how to use the pipe fail option to ignore errors.

#!/bin/bash

# Example of ignoring errors using pipefail

# The `command1` will fail but it will not stop execution
set -o pipefail
command1 | command2

# Rest of the script

In this example, command1 will fail, but command2 will continue to execute, and the script will not stop execution.

Undefined Variables

By default, Bash will stop the execution of a script if an undefined variable is used. However, you can use the -u option to ignore this behavior and continue running the script even if an undefined variable is used. The following example demonstrates how to ignore undefined variables.

#!/bin/bash

# Example of ignoring undefined variables

set +u

echo $undefined_variable

# Rest of the script

In this example, the script will not stop execution when an undefined variable is used.

Compiling and Interpreting

When compiling or interpreting a script, errors may occur. However, these errors can be ignored by using the -f option when running the script. The following example demonstrates how to ignore errors when compiling or interpreting a script.

#!/bin/bash

# Example of ignoring errors when compiling or interpreting

bash -f script.sh

# Rest of the script

In this example, the script will continue to run even if there are errors during the compilation or interpretation process.

Traps

A trap is a way to execute a command or a set of commands when a specific signal is received by the script. This can be useful when you want to ignore errors and run a cleanup command instead. The following example demonstrates how to use a trap to ignore errors.

#!/bin/bash

# Example of ignoring errors using a trap

# Set a trap to run the cleanup function when an error occurs
trap cleanup ERR

# Function to run when an error occurs
cleanup() {
  echo "Cleaning up before exiting..."
}

# Command that will cause an error
command_that_will_fail

# Rest of the script

In this example, when the command_that_will_fail causes an error, the script will execute the cleanup function instead of stopping execution. This allows you to perform any necessary cleanup before exiting the script.

Examples of Bash for Error Handling:

Example 1: Error Handling Using a Conditional Condition

One way to handle errors in Bash is to use a conditional statement. The following example demonstrates how to check for a specific error and handle it accordingly.

#!/bin/bash

# Example of error handling using a conditional condition

file=example.txt

if [ ! -f $file ]; then
  echo "Error: $file does not exist"
  exit 1
fi

# Rest of the script

In this example, we check if the file “example.txt” exists using the -f option of the [ command. If the file does not exist, the script will print an error message and exit with a status code of 1. This allows the script to continue running if the file exists and exit if it does not.

Example 2: Error Handling Using the Exit Status Code

Another way to handle errors in Bash is to check the exit status code of a command. Every command in Bash returns an exit status code when it completes, with a code of 0 indicating success and any other code indicating an error. The following example demonstrates how to check the exit status code of a command and handle it accordingly.

#!/bin/bash

# Example of error handling using the exit status code

command1

if [ $? -ne 0 ]; then
  echo "Error: command1 failed"
  exit 1
fi

# Rest of the script

In this example, the script runs the command “command1” and then checks the exit status code using the special variable $?. If the exit status code is not 0, the script will print an error message and exit with a status code of 1.

Example 3: Stop the Execution on the First Error

When running a script, it can be useful to stop the execution on the first error that occurs. This can be achieved by using the set -e command, which tells Bash to exit the script if any command exits with a non-zero status code.

#!/bin/bash

# Stop execution on the first error

set -e

command1
command2
command3

# Rest of the script

In this example, if any of the commands “command1”, “command2” or “command3” fail, the script will exit immediately.

Example 4: Stop the Execution for Uninitialized Variable

Another way to stop execution on error is if an uninitialized variable is used during script execution. This can be achieved by using the set -u command, which tells Bash to exit the script if any uninitialized variable is used.

#!/bin/bash

# Stop execution for uninitialized variable

set -u

echo $uninitialized_variable

# Rest of the script

In this example, if the uninitialized_variable is not defined, the script will exit immediately.

Conclusion

In conclusion, understanding and ignoring errors in Bash is an important aspect of working with the command-line interface. By checking the exit status code of a command, its associated error message, and redirecting the stderr to a file or the stdout, you can understand what went wrong. And by using the command || true, command 2> /dev/null, command 2>&1 >/dev/null, and command || : constructs, you can ignore errors when necessary. It’s always a good practice to test these constructs in a testing environment before using them in production.

Понравилась статья? Поделить с друзьями:
  • Basenamedobjects wmiprovidersubsystemhostjob win32 error 1060
  • Basecomm smx basic comm control unexpected error 23 in askpluginload callback
  • Base game not installed application will exit как исправить
  • Base error unhandled exception inputmapper
  • Base error 7405602 argument parse error