46

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!

  • 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 07:42

6 Answers6

53

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 `&'"

peter_v
  • 103
Nidal
  • 8,956
19

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
graphite
  • 501
10

To return the error message in a variable, simply;

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

echo $error
Prvt_Yadav
  • 5,882
Henry
  • 200
  • 2
    That's the answer, since the other ones would append standard output to the variable. Usually, you want to know if the message comes from a error or not and that's perfect. For example, to throw a warning or to handle a bad situation in a script. – R. W. Prado Sep 15 '21 at 20:48
6

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
$ 
4

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

4

I capture error like this

. ${file} 2>&1 | {
  read -d "\0" -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

wener
  • 466