Skip to content

How to Store Standard Error to a Variable in Bash

In Bash, you can store the standard error output of a command to a variable by using the `2>&1` operator and the `$()` command substitution syntax. Here `2>` redirects the error message to &1`, that represent to standard output. In the case of bash shell works as the standard output device.

  • For example, to store the standard error output of the `ls` command to a variable named errors, you can use the following command:
    errors=$(ls non-existent-file 2>&1) 
    
    Store Standard Error in a Bash Variable
    Store Standard Error in a Bash Variable

    Alternatively, you can use the `$?` special parameter to store the exit status of a command to a variable. The exit status is a numeric value that indicates whether the command was successful or not. A value of `0` indicates success, while a non-zero value indicates an error.

  • For example, to store the exit status of the `ls` command to a variable named status, you can use the following command:
    ls non-existent-file 
    status=$? 
    
  • You can then use the `$status` variable to check the exit status of the `ls` command and take appropriate action based on the result. For example:

Keep in mind that the `$()` command substitution syntax allows you to execute a command and substitute its output in place. The `2>` operator redirects the standard error output of the command to the `&1` stream, which is the standard output stream. This allows you to capture both the standard output and standard error output of the command in a single variable.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top