Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»General Articles»How to Store Standard Error to a Variable in Bash

    How to Store Standard Error to a Variable in Bash

    By RahulDecember 23, 20222 Mins Read

    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.

    Advertisement
    • 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:

      1
      2
      3
      4
      5
      6
      #!/usr/bin/env bash
       
      # Pur your commands here
      if [ $status -ne 0 ]; then
        echo "Last command failed with an error."
      fi

    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.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to Install PHP 8.2-7.4 on RHEL & CentOS Stream 9

    How to Install MySQL 8.0 on RHEL & CentOS Stream 9

    How to Split Large Archives in Linux using the Command Line

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • What is the /etc/mtab File in Linux
    • The “Hello World” Challenge: Printing in 20 Different Programming Languages
    • How to Install PHP 8.2-7.4 on RHEL & CentOS Stream 9
    • How to Install MySQL 8.0 on RHEL & CentOS Stream 9
    • How to Split Large Archives in Linux using the Command Line
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.