variables inside trap command in BASH

Hello folks,

I've experimented a bit with bash's trap command and I've found rather strange behaviour. Searching threads about it on the forum gave me no useful results.

Here my question is. Consider this little script:
Code:
#!/usr/local/bin/bash

function trapping() {
local error_message="$1"
echo -e "error is $1";
}

trap "{ trapping \$ERRORR ; }" EXIT

ERRORR="Your script does not work."
echo -n "Please, write here anything: "
read MYVAL

test -z $MYVAL && \
{
ERRORR="Some error message."
exit 0
}

The output is:
Code:
Please, write here anything: 
error is Some

So, as you can see, any text that follows whitespace in the ERRORR's value is ignored. I still can add \t or some other escape sequences instead of whitespace and it will work. But is there any way to quote $ERRORR variable properly in the trap?
 
Fors said:
So, as you can see, any text that follows whitespace in the ERRORR's value is ignored.

That's because you are passing to the trapping() functions 3 parameters: "Some", "error" and "message". In your code you are printing only the first ($1), but you have to print them all ($*):
Code:
function trapping() {
[color=RED]-local error_message="$1"
-echo -e "error is $1";[/color][color=GREEN]
+local error_message="$*"
+echo -e "error is $error_message"[/color]
}
 
Oh thank you,

I actually was trying to pass a string to the function as the only one parameter. In case I need to do something more in trapping() function, I might need to pass some another parameter, therefore $* will not serve well.

But I have to say, that your solution for my simple script is what I need.
 
Fors said:
I actually was trying to pass a string to the function as the only one parameter. In case I need to do something more in trapping() function, I might need to pass some another parameter, therefore $* will not serve well.

In this case, you could leave the trapping() function as it was in origin and change only this:
Code:
[color=RED]-trap "{ trapping \$ERRORR ; }" EXIT[/color]
[color=GREEN]+trap "{ trapping \"\$ERRORR\" ; }" EXIT[/color]
 
Dies_Irae said:
In this case, you could leave the trapping() function as it was in origin and change only this:
Code:
[color=RED]-trap "{ trapping \$ERRORR ; }" EXIT[/color]
[color=GREEN]+trap "{ trapping \"\$ERRORR\" ; }" EXIT[/color]

Many thanks, it works amazingly! I always have a hard time trying to use quotes properly :r
 
Back
Top