Bash - Save errors in a variable

0

I am running a bash script that saves the error messages in a .txt log file, I need to save the error messages in a variable now, following example:

LOG="/home/control/log.txt"
exec 2>>$LOG
tar -zcf teste.tar.gz teste

It zips the test folder and writes the errors to log.txt I need q to write to a variable to print the errors!

    
asked by anonymous 20.07.2016 / 22:48

3 answers

1

foobar.sh :

#!/bin/bash
VAR=$(tar -zcf foobar.tar.gz foo.txt bar.txt )
echo "${VAR}"
exit 0

Testing:

$ ./foobar.sh 
tar: foo.txt: Cannot stat: No such file or directory
tar: bar.txt: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
    
21.07.2016 / 00:00
1

maybe

LOG="/home/control/log.txt"
tar -zcf teste.tar.gz teste 2>>$LOG
    
12.09.2016 / 21:25
0

Why do you "need" to put in a variable? I think this is questionable, but anyway ...

It seems the best way is to follow this suggestion link :

Run everything in a sub-shell and redirect the output of errors to the standard output, which is captured by the ERRORS variable. In the sub-shell, the default output is ignored (redirected to / dev / null). It's interesting.

ERRORS=$( (tar -zcf teste.tar.gz teste > /dev/null) 2>&1 )

PS 1 : just like in the English OS, I did not test the solution ... PS 2 : keys are used in the original to run the sub-shell, but I think the most common is to use parentheses same as PS 3 : in the original it has a ';' before the internal parenthesis, so ...teste ; ) , I do not know if I really need it

    
24.09.2016 / 05:32