# variables inside trap command in BASH



## Fors (Jun 6, 2013)

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:

```
#!/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:

```
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?


----------



## Dies_Irae (Jun 6, 2013)

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 ($*):

```
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]
}
```


----------



## Fors (Jun 6, 2013)

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.


----------



## Dies_Irae (Jun 6, 2013)

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:

```
[color=RED]-trap "{ trapping \$ERRORR ; }" EXIT[/color]
[color=GREEN]+trap "{ trapping \"\$ERRORR\" ; }" EXIT[/color]
```


----------



## Fors (Jun 7, 2013)

Dies_Irae said:
			
		

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



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


----------

