How to capture error message from executed command?bash script is trying to execute a variableSeparate...

Ito`s Lemma problem

Determine the slope and write the Cartesian equation of the line.

Jesus' words on the Jews

How does emacs `shell-mode` know to prompt for sudo?

Area under the curve - Integrals (Antiderivatives)

Rounding a number extracted by jq to limit the decimal points

Could there be a material that inverts the colours seen through it?

When a land becomes a creature, is it untapped?

correct spelling of "carruffel" (fuzz, hustle, all that jazz)

How do employ ' ("prime") in math mode at the correct depth?

Do Life Drain attacks from wights stack?

German characters on US-International keyboard layout

Does SQL Server allow (make visible) DDL inside a transaction to the transaction prior to commit?

Why do the lights go out when someone enters the dining room on this ship?

Smallest Guaranteed hash collision cycle length

Quote from Leibniz

What are the implications of the new alleged key recovery attack preprint on SIMON?

Is this apt vulnerability (CVE-2019-3462) a security concern for Ubuntu users?

using `is` operator with value type tuples gives error

Program which behaves differently in/out of a debugger

Safety when modifying old electrical work

How much Replacement does this axiom provide?

Missouri raptors have wild hairdos

Anatomically Correct Carnivorous Tree



How to capture error message from executed command?


bash script is trying to execute a variableSeparate filename and path inside find command's -exec optiongenerate file names in loopHow to stamp prompt at command execute time?How to select and output text in a stringHow to avoid `command not found` error when re-sourcing bash configuration with a key binding?Getting no output from command substitution?Strategy for forgetting to run a script with `source`?Treating the input for the read command as a command itselfRe-running a command in case of a specific error message






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







16















I was tasked to create an automated server hardening script and one thing that they need is a report of all the output of each command executed. I want to store the error message inside a string and append it in a text file.



Let's say I ran this command:



/sbin/modprobe -n -v hfsplus


The output of running this in my machine would be:



FATAL: Module hfsplus not found


How can I store that error message inside a string? Any help would be greatly appreciated. Thanks!










share|improve this question























  • I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn't capture the error message inside the string.

    – Miguel Roque
    May 29 '14 at 7:42




















16















I was tasked to create an automated server hardening script and one thing that they need is a report of all the output of each command executed. I want to store the error message inside a string and append it in a text file.



Let's say I ran this command:



/sbin/modprobe -n -v hfsplus


The output of running this in my machine would be:



FATAL: Module hfsplus not found


How can I store that error message inside a string? Any help would be greatly appreciated. Thanks!










share|improve this question























  • I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn't capture the error message inside the string.

    – Miguel Roque
    May 29 '14 at 7:42
















16












16








16


5






I was tasked to create an automated server hardening script and one thing that they need is a report of all the output of each command executed. I want to store the error message inside a string and append it in a text file.



Let's say I ran this command:



/sbin/modprobe -n -v hfsplus


The output of running this in my machine would be:



FATAL: Module hfsplus not found


How can I store that error message inside a string? Any help would be greatly appreciated. Thanks!










share|improve this question














I was tasked to create an automated server hardening script and one thing that they need is a report of all the output of each command executed. I want to store the error message inside a string and append it in a text file.



Let's say I ran this command:



/sbin/modprobe -n -v hfsplus


The output of running this in my machine would be:



FATAL: Module hfsplus not found


How can I store that error message inside a string? Any help would be greatly appreciated. Thanks!







bash scripting string






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 29 '14 at 7:25









Miguel RoqueMiguel Roque

3254514




3254514













  • I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn't capture the error message inside the string.

    – Miguel Roque
    May 29 '14 at 7:42





















  • I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn't capture the error message inside the string.

    – Miguel Roque
    May 29 '14 at 7:42



















I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn't capture the error message inside the string.

– Miguel Roque
May 29 '14 at 7:42







I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn't capture the error message inside the string.

– Miguel Roque
May 29 '14 at 7:42












6 Answers
6






active

oldest

votes


















19














you can do it by redirecting errors command:



/sbin/modprobe -n -v hfsplus 2> fileName 


as a script



#!/bin/bash
errormessage=$( /sbin/modprobe -n -v hfsplus 2>&1)
echo $errormessage


or



 #!/bin/bash
errormessage=`/sbin/modprobe -n -v hfsplus 2>&1 `
echo $errormessage


if you want to append the error use >> instead of >



Make sure to use 2>&1 and not 2> &1 to avoid the error
"syntax error near unexpected token `&'"






share|improve this answer


























  • I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

    – Miguel Roque
    May 29 '14 at 7:45






  • 1





    @MiguelRoque see updates

    – Networker
    May 29 '14 at 7:46






  • 1





    I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

    – Miguel Roque
    May 29 '14 at 7:52






  • 1





    Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

    – Pierre.Sassoulas
    Jan 12 '18 at 10:08











  • I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

    – peter_v
    Jun 28 '18 at 8:14



















14














Simply to store as a string in bash script:



X=`/sbin/modprobe -n -v hfsplus 2>&1`
echo $X


This can be a bit better as you will see messages when command is executed:



TMP=$(mktemp)
/sbin/modprobe -n -v hfsplus 2>&1 | tee $TMP
OUTPUT=$(cat $TMP)
echo $OUTPUT
rm $TMP





share|improve this answer





















  • 1





    Always use $(command) instead of backticks for command substitution. It is better :)

    – Sree
    Feb 13 '15 at 7:02





















4














I capture error like this



. ${file} 2>&1 | {
read -d "" -t 0.01 error
[ -z "$error" ] || log_warn Load completion ${file} failed: "n${error}"
}


if source failed, I will capture the error and log it.log_warn is just a simple function.



BTW, I use this in my dotfiles






share|improve this answer































    2














    To append to a file use /sbin/modprobe -n -v hfsplus 2>> filename






    share|improve this answer

































      2














      Newer bash versions (I.e. bash 4.1+):



      $ msg=$(ls -la nofile 2>&1)
      $ echo $msg
      ls: cannot access nofile: No such file or directory
      $





      share|improve this answer































        0














        To return the error message in a variable, simply;



        error=$(/sbin/modprobe -n -v hfsplus 2>&1 1>/dev/null)

        echo $error





        share|improve this answer


























          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "106"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f132511%2fhow-to-capture-error-message-from-executed-command%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          19














          you can do it by redirecting errors command:



          /sbin/modprobe -n -v hfsplus 2> fileName 


          as a script



          #!/bin/bash
          errormessage=$( /sbin/modprobe -n -v hfsplus 2>&1)
          echo $errormessage


          or



           #!/bin/bash
          errormessage=`/sbin/modprobe -n -v hfsplus 2>&1 `
          echo $errormessage


          if you want to append the error use >> instead of >



          Make sure to use 2>&1 and not 2> &1 to avoid the error
          "syntax error near unexpected token `&'"






          share|improve this answer


























          • I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

            – Miguel Roque
            May 29 '14 at 7:45






          • 1





            @MiguelRoque see updates

            – Networker
            May 29 '14 at 7:46






          • 1





            I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

            – Miguel Roque
            May 29 '14 at 7:52






          • 1





            Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

            – Pierre.Sassoulas
            Jan 12 '18 at 10:08











          • I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

            – peter_v
            Jun 28 '18 at 8:14
















          19














          you can do it by redirecting errors command:



          /sbin/modprobe -n -v hfsplus 2> fileName 


          as a script



          #!/bin/bash
          errormessage=$( /sbin/modprobe -n -v hfsplus 2>&1)
          echo $errormessage


          or



           #!/bin/bash
          errormessage=`/sbin/modprobe -n -v hfsplus 2>&1 `
          echo $errormessage


          if you want to append the error use >> instead of >



          Make sure to use 2>&1 and not 2> &1 to avoid the error
          "syntax error near unexpected token `&'"






          share|improve this answer


























          • I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

            – Miguel Roque
            May 29 '14 at 7:45






          • 1





            @MiguelRoque see updates

            – Networker
            May 29 '14 at 7:46






          • 1





            I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

            – Miguel Roque
            May 29 '14 at 7:52






          • 1





            Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

            – Pierre.Sassoulas
            Jan 12 '18 at 10:08











          • I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

            – peter_v
            Jun 28 '18 at 8:14














          19












          19








          19







          you can do it by redirecting errors command:



          /sbin/modprobe -n -v hfsplus 2> fileName 


          as a script



          #!/bin/bash
          errormessage=$( /sbin/modprobe -n -v hfsplus 2>&1)
          echo $errormessage


          or



           #!/bin/bash
          errormessage=`/sbin/modprobe -n -v hfsplus 2>&1 `
          echo $errormessage


          if you want to append the error use >> instead of >



          Make sure to use 2>&1 and not 2> &1 to avoid the error
          "syntax error near unexpected token `&'"






          share|improve this answer















          you can do it by redirecting errors command:



          /sbin/modprobe -n -v hfsplus 2> fileName 


          as a script



          #!/bin/bash
          errormessage=$( /sbin/modprobe -n -v hfsplus 2>&1)
          echo $errormessage


          or



           #!/bin/bash
          errormessage=`/sbin/modprobe -n -v hfsplus 2>&1 `
          echo $errormessage


          if you want to append the error use >> instead of >



          Make sure to use 2>&1 and not 2> &1 to avoid the error
          "syntax error near unexpected token `&'"







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 28 '18 at 10:43









          peter_v

          1034




          1034










          answered May 29 '14 at 7:42









          NetworkerNetworker

          6,146104270




          6,146104270













          • I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

            – Miguel Roque
            May 29 '14 at 7:45






          • 1





            @MiguelRoque see updates

            – Networker
            May 29 '14 at 7:46






          • 1





            I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

            – Miguel Roque
            May 29 '14 at 7:52






          • 1





            Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

            – Pierre.Sassoulas
            Jan 12 '18 at 10:08











          • I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

            – peter_v
            Jun 28 '18 at 8:14



















          • I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

            – Miguel Roque
            May 29 '14 at 7:45






          • 1





            @MiguelRoque see updates

            – Networker
            May 29 '14 at 7:46






          • 1





            I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

            – Miguel Roque
            May 29 '14 at 7:52






          • 1





            Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

            – Pierre.Sassoulas
            Jan 12 '18 at 10:08











          • I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

            – peter_v
            Jun 28 '18 at 8:14

















          I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

          – Miguel Roque
          May 29 '14 at 7:45





          I've tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

          – Miguel Roque
          May 29 '14 at 7:45




          1




          1





          @MiguelRoque see updates

          – Networker
          May 29 '14 at 7:46





          @MiguelRoque see updates

          – Networker
          May 29 '14 at 7:46




          1




          1





          I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

          – Miguel Roque
          May 29 '14 at 7:52





          I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker!

          – Miguel Roque
          May 29 '14 at 7:52




          1




          1





          Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

          – Pierre.Sassoulas
          Jan 12 '18 at 10:08





          Someone reverted the edit I did, because I had a "syntax error near &" and removed the space after >. A justification would have been nice.

          – Pierre.Sassoulas
          Jan 12 '18 at 10:08













          I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

          – peter_v
          Jun 28 '18 at 8:14





          I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error "syntax error near unexpected token `&'"

          – peter_v
          Jun 28 '18 at 8:14













          14














          Simply to store as a string in bash script:



          X=`/sbin/modprobe -n -v hfsplus 2>&1`
          echo $X


          This can be a bit better as you will see messages when command is executed:



          TMP=$(mktemp)
          /sbin/modprobe -n -v hfsplus 2>&1 | tee $TMP
          OUTPUT=$(cat $TMP)
          echo $OUTPUT
          rm $TMP





          share|improve this answer





















          • 1





            Always use $(command) instead of backticks for command substitution. It is better :)

            – Sree
            Feb 13 '15 at 7:02


















          14














          Simply to store as a string in bash script:



          X=`/sbin/modprobe -n -v hfsplus 2>&1`
          echo $X


          This can be a bit better as you will see messages when command is executed:



          TMP=$(mktemp)
          /sbin/modprobe -n -v hfsplus 2>&1 | tee $TMP
          OUTPUT=$(cat $TMP)
          echo $OUTPUT
          rm $TMP





          share|improve this answer





















          • 1





            Always use $(command) instead of backticks for command substitution. It is better :)

            – Sree
            Feb 13 '15 at 7:02
















          14












          14








          14







          Simply to store as a string in bash script:



          X=`/sbin/modprobe -n -v hfsplus 2>&1`
          echo $X


          This can be a bit better as you will see messages when command is executed:



          TMP=$(mktemp)
          /sbin/modprobe -n -v hfsplus 2>&1 | tee $TMP
          OUTPUT=$(cat $TMP)
          echo $OUTPUT
          rm $TMP





          share|improve this answer















          Simply to store as a string in bash script:



          X=`/sbin/modprobe -n -v hfsplus 2>&1`
          echo $X


          This can be a bit better as you will see messages when command is executed:



          TMP=$(mktemp)
          /sbin/modprobe -n -v hfsplus 2>&1 | tee $TMP
          OUTPUT=$(cat $TMP)
          echo $OUTPUT
          rm $TMP






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 29 '14 at 8:06

























          answered May 29 '14 at 7:47









          graphitegraphite

          43147




          43147








          • 1





            Always use $(command) instead of backticks for command substitution. It is better :)

            – Sree
            Feb 13 '15 at 7:02
















          • 1





            Always use $(command) instead of backticks for command substitution. It is better :)

            – Sree
            Feb 13 '15 at 7:02










          1




          1





          Always use $(command) instead of backticks for command substitution. It is better :)

          – Sree
          Feb 13 '15 at 7:02







          Always use $(command) instead of backticks for command substitution. It is better :)

          – Sree
          Feb 13 '15 at 7:02













          4














          I capture error like this



          . ${file} 2>&1 | {
          read -d "" -t 0.01 error
          [ -z "$error" ] || log_warn Load completion ${file} failed: "n${error}"
          }


          if source failed, I will capture the error and log it.log_warn is just a simple function.



          BTW, I use this in my dotfiles






          share|improve this answer




























            4














            I capture error like this



            . ${file} 2>&1 | {
            read -d "" -t 0.01 error
            [ -z "$error" ] || log_warn Load completion ${file} failed: "n${error}"
            }


            if source failed, I will capture the error and log it.log_warn is just a simple function.



            BTW, I use this in my dotfiles






            share|improve this answer


























              4












              4








              4







              I capture error like this



              . ${file} 2>&1 | {
              read -d "" -t 0.01 error
              [ -z "$error" ] || log_warn Load completion ${file} failed: "n${error}"
              }


              if source failed, I will capture the error and log it.log_warn is just a simple function.



              BTW, I use this in my dotfiles






              share|improve this answer













              I capture error like this



              . ${file} 2>&1 | {
              read -d "" -t 0.01 error
              [ -z "$error" ] || log_warn Load completion ${file} failed: "n${error}"
              }


              if source failed, I will capture the error and log it.log_warn is just a simple function.



              BTW, I use this in my dotfiles







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Feb 13 '15 at 6:22









              wenerwener

              27127




              27127























                  2














                  To append to a file use /sbin/modprobe -n -v hfsplus 2>> filename






                  share|improve this answer






























                    2














                    To append to a file use /sbin/modprobe -n -v hfsplus 2>> filename






                    share|improve this answer




























                      2












                      2








                      2







                      To append to a file use /sbin/modprobe -n -v hfsplus 2>> filename






                      share|improve this answer















                      To append to a file use /sbin/modprobe -n -v hfsplus 2>> filename







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 29 '14 at 7:52

























                      answered May 29 '14 at 7:44









                      harish.venkatharish.venkat

                      4,75312027




                      4,75312027























                          2














                          Newer bash versions (I.e. bash 4.1+):



                          $ msg=$(ls -la nofile 2>&1)
                          $ echo $msg
                          ls: cannot access nofile: No such file or directory
                          $





                          share|improve this answer




























                            2














                            Newer bash versions (I.e. bash 4.1+):



                            $ msg=$(ls -la nofile 2>&1)
                            $ echo $msg
                            ls: cannot access nofile: No such file or directory
                            $





                            share|improve this answer


























                              2












                              2








                              2







                              Newer bash versions (I.e. bash 4.1+):



                              $ msg=$(ls -la nofile 2>&1)
                              $ echo $msg
                              ls: cannot access nofile: No such file or directory
                              $





                              share|improve this answer













                              Newer bash versions (I.e. bash 4.1+):



                              $ msg=$(ls -la nofile 2>&1)
                              $ echo $msg
                              ls: cannot access nofile: No such file or directory
                              $






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 4 '17 at 10:58









                              BurningKromeBurningKrome

                              1235




                              1235























                                  0














                                  To return the error message in a variable, simply;



                                  error=$(/sbin/modprobe -n -v hfsplus 2>&1 1>/dev/null)

                                  echo $error





                                  share|improve this answer






























                                    0














                                    To return the error message in a variable, simply;



                                    error=$(/sbin/modprobe -n -v hfsplus 2>&1 1>/dev/null)

                                    echo $error





                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      To return the error message in a variable, simply;



                                      error=$(/sbin/modprobe -n -v hfsplus 2>&1 1>/dev/null)

                                      echo $error





                                      share|improve this answer















                                      To return the error message in a variable, simply;



                                      error=$(/sbin/modprobe -n -v hfsplus 2>&1 1>/dev/null)

                                      echo $error






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Feb 8 at 11:49









                                      Prvt_Yadv

                                      3,40731532




                                      3,40731532










                                      answered Feb 8 at 10:56









                                      JonathanJonathan

                                      11




                                      11






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f132511%2fhow-to-capture-error-message-from-executed-command%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                          Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                          Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...