trap error and assign in bash script
hi
I try to assign return from a _error_handler_function to a variable this is just a test( dummy test ) not a really case #!/bin/bash logfile="/dev/shm/log.err" exec 2>$logfile _err_handler(){ v=$(cat $logfile|grep dummy|wc -l); rm $logfile echo $v } trap _err_handler ERR x=$(dummy); echo "x value is $x " z=$(notrap) echo "z value is $z" expected output : bash-4.1$ sh test2.sh x value is 1 z value is 0 what is wrong here and how should I fix? thanks in advance |
Interesting problem. I have never used trap (although it has been on my todo list for a while) so I can't give you a fix, but I think I can see what goes wrong.
When you call dummy the error handler is invoked, but you are not in the context of the invoking call anymore, so the variable assignment never happens. If you add Code:
x=$v Code:
user@localhost:~$ ./test.sh |
How is this
Code:
#!/bin/bash |
So here is another alternative. Basically I do not like passing around global variables if I can help it. Also, I wasn't sure if we should be completely removing the logfile or just truncating?
My thought here was that you want the code to keep running but by removing it you have broken the link to the file and left a dangling exec with no closure. So here is what I have: Code:
logfile="/tmp/log.err" |
thank you both!!
i'm wondering if there is a way to change _error_handler to also allow use directly in test condition: [[ 0 -lt $(dummy) ]] && echo "is a dummy (test)" instead of assignment and test x=$(dummy); [[ 0 -lt $x ]] && echo " has a dummy" |
I am not sure I follow? Why not just test $? after the assignment and if errored (> 0) then do what you need?
Overall it may help if you explained what you actually need as grepping the error in a file when you know it will happen seems a little pointless. |
Quote:
That said, I'll allow myself to point out that your code still ends up using global variables. |
Quote:
|
Quote:
|
All times are GMT -5. The time now is 03:35 AM. |