Search code examples
bashshellreroute

How to assign the result of mysqldump command into a variable?


In my bash script, I have tried

dumpresult=$(mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} > ${desdir}/${filename_sql})

and

dumpresult=`mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} > ${desdir}/${filename_sql}`

and

dumpresult=$(echo `mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} > ${desdir}/${filename_sql}`)

and

dumpresult=$(echo 'mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} > ${desdir}/${filename_sql}')

to get the result of the mysqldump command into a variable (in case of an error). However $dumpresult will remain empty. Any idea?

To make it clear, I need the mysqldump in a file (that works fine already) and the mysqldump error messages of stderr in $dumpresult.

Thanks a lot,

G.


Solution

  • You assign the standard output of the command to a variable, but since you redirect the stdout to a file, there is no stdout at all.

    You can verify this by doing just a

    mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} > ${desdir}/${filename_sql} 2>/dev/null
    

    You will see that nothing is printed. Consequently, if you would assign the output to your variable, the variable would be empty.

    To get the stdout to a file and into your variable, you have to do one of these:

    dumpresult=$(mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} | tee ${desdir}/${filename_sql})
    

    or

    mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} > ${desdir}/${filename_sql}
    dumpresult=$(<${desdir}/${filename_sql})
    

    UPDATE

    If you are interested in the stderr of the mysqldump, I suggest to use

    dumpresult=$( (mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} | tee ${desdir}/${filename_sql}) 2>&1 )
    

    or

    dumpresult=$(mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} 3>&1 1>${desdir}/${filename_sql} 2>&3)
    

    (UPDATE)

    or even simpler

    dumpresult=$(mysqldump --user="${dbuser}" --password="${dbpw}" ${dbname} 2>&1 >${desdir}/${filename_sql}