Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 yesterday
add comment

3 Answers

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
add comment

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 >

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 yesterday
1  
@MiguelRoque see updates –  Networker yesterday
1  
I tried putting the output inside a HEREDOC and it worked also. Thanks a lot @Networker! –  Miguel Roque yesterday
    
@graphite thanks edited –  Networker yesterday
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.