I have this simple script which redirects the output and append it to a file.filename=/home/ronnie/tmp/hellodate=$(date)echo $date >> $filenameNow, lets suppose I change date=$(date) to date= $(date) which will generate an error. My modified script:filename=/home/ronnie/tmp/hellodate= $(date)echo $date >> $filename 2>> $filename #Also tried echo $date >> $filename 2>&1I was thinking that above script will redirect the error test.sh: line 5: Fri: command not found to the file hello but it just enters a new line into the file and the error gets printed on my stdout.My bash version:ronnier@ronnie:~/tmp$ bash --versionGNU bash, version 4.2.24(1)-release (i686-pc-linux-gnu)So, where am I going wrong.
How to redirect error to a file?
bash;stdout;stderr
The line which causes the error is date =$(date), that error is sent to stderr.  At that stage, you're not redirecting stderr anywhere.  The subsequent line sends stderr to $filename, but it's not that line which causes the error.One of the ways to get the effect you want, you would run your script and direct stderr to somewhere else at the same time, so,./myscript 2>> errors.txtat that point, errors.txt will contain your error.So the issue is, the line generating the error is an error in the script itself, not an error caused by an external command the script calls which has it's output redirected.  i.e. it's the top level script output you need to redirect.