Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error output and store it in a variable or file

I'm having a little trouble figuring out how to get error output and store it in a variable or file in ksh. So in my script I have cp -p source.file destination inside a while loop.

When I get the below error

cp: source.file: The file access permissions do not allow the specified action.

I want to grab it and store it in a variable or file.

Thanks

like image 302
esausilva Avatar asked Oct 12 '25 19:10

esausilva


1 Answers

You can redirect the error output of the command like so:

cp -p source.file destination 2>> my_log.txt

It will append the error message to the my_log.txt file.

In case you want a variable you can redirect stderr to stdout and assign the command output to a variable:

my_error_var=$(cp -p source.file destination 2>&1)
like image 54
Bernhard Avatar answered Oct 14 '25 12:10

Bernhard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!