Bash - Save errors in a variable

Asked

Viewed 541 times

0

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

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

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

3 answers

2

maybe

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

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
  • I ran this code that you gave me but did not print the errors in the variable, it was empty!

  • @A.S.: Perhaps the variable was empty because the command tar displays a 'silent' behavior when successful.

  • If you put a -v in tar -zcvf it will print on STDOUT even if tar runs successfully

0

Why do you "need" to put in a variable ? I find it questionable, but anyway...

It seems the best way is to follow this suggestion of https://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script:

Run everything in a sub-shell and redirect the error output to the standard output, which is captured by the ERRORS variable. In the sub-shell, the default output is ignored (redirected to /dev/null). Interesting.

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

PS 1: as in the OS in English, I have not tested the solution...
PS 2: in the original are used {} keys to run the subshell, but I think the most common is to use same parentheses
PS 3: in the original has a ';' before the inner parenthesis, thus ...teste ; ), I don’t know if you really need to

Browser other questions tagged

You are not signed in. Login or sign up in order to post.