0

I am writing a new script for a backup solution. Now I want to get the error message, which I saw in terminal, to a log file. Therefor I want to write the output in a variable.

I wrote an error in it. The option "defaults-file" is missing a "--".

With a simple example it worked:

#!/bin/bash
log=$(date)
echo $log

This is the code snippet:

#!/bin/bash
DATE=`date +\%Y\%m\%d\%H\%M\%S`.sql
log=$(`mysqldump defaults-file=/home/user/.my.cnf cloud > backup_$DATE`)

echo $log
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
muelleste
  • 41
  • 1
  • 1
  • 3
  • 2
    Use backticks **or** `$( )`, not both. `$( )` is preferred, see [BashFAQ #82](http://mywiki.wooledge.org/BashFAQ/082). BTW, I don't think this is quite a duplicate, since if I'm reading it right, the goal is to capture stderr in a variable, *and* redirect stdout to a file. – Gordon Davisson Feb 19 '19 at 08:02

1 Answers1

2

You are not capturing any string in log because your mysql command is sending all its standard output to a file.

Capturing standard output in a variable so that you can echo that variable to standard output is an antipattern anyway (and a bug if you don't double-quote the string you echo).

If you want to redirect the standard error output to standard output, use another redirection.

#!/bin/bash
# Also, don't use uppercase for private variables
# and prefer $(command) over obsolescent `command`
date=$(date +%Y%m%d%H%M%S).sql
mysqldump defaults-file=/home/user/.my.cnf cloud 2>&1 > "backup_$DATE"

The 2>&1 redirect causes error messages to go to the standard output file descriptor. The > redirect causes the (original) standard output to go to a file.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • @JohnKugelman Rolled back your edit. The intent is precisely to get stdout and stderr to two different places. – tripleee Feb 21 '19 at 05:00