45

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!

Miguel Roque
  • 905
  • 4
  • 11
  • 14
  • 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

52

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
  • 4
Nidal
  • 8,856
  • 11
  • 55
  • 74
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
  • 4
  • 7
9

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,732
  • 7
  • 32
  • 48
Jonathan
  • 190
  • 1
  • 3
  • 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
$ 
BurningKrome
  • 228
  • 4
  • 11
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
  • 456
  • 3
  • 9
3

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

harish.venkat
  • 7,313
  • 2
  • 25
  • 30