Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trap function by passing arguments?

I've been searching everywhere and I've come to believe that there is no way to do that other than having global variables but I believe the guru's in stackoverflow.com may be able to help me:

Is there any way in bash to trap a function by passing arguments to it?
For example, trap <function_name> <arg_1> <arg_2> SIGINT?

like image 437
Kounavi Avatar asked Feb 29 '12 18:02

Kounavi


People also ask

How do you pass an argument to a shell function?

To invoke a function, simply use the function name as a command. To pass parameters to the function, add space separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.

How do you pass an argument to a function in bash?

To pass any number of arguments to the bash function simply put them right after the function's name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it. The passed parameters are $1 , $2 , $3 …

What is trap function?

Traps are devices that delimit the displacement of previously free-ranging entities in space through time. Examples of traps used for prey capture by organisms other than humans are spider webs, ant-lion traps, and the Venus fly trap. Traps offer efficiencies to their makers by concentrating the target organisms.

What is trap in shell scripting?

trap defines and activates handlers to run when the shell receives signals or other special conditions. ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC.


3 Answers

trap lets you specify an arbitrary command (or sequence of commands), but you have to pass that command as a single argument. For example, this:

trap 'foo bar baz | bip && fred barney ; wilma' SIGINT

will run this:

foo bar baz | bip && fred barney ; wilma

whenever the shell receives SIGINT. In your case, it sounds like you want:

trap '<function> <arg_1> <arg_2>' SIGINT
like image 100
ruakh Avatar answered Sep 30 '22 21:09

ruakh


Maybe I'm misunderstanding you, but ... this is legal:

trap "cp /etc/passwd $HOME/p" SIGINT
trap 'cp /etc/passwd /tmp/p; echo wooo hoo' SIGINT
like image 21
rsaw Avatar answered Sep 30 '22 19:09

rsaw


I'm not sure I understand correctly what you mean, but if you want to make a signal handler call a function and pass it parameters, trap "function arg1 arg2" SIGNAL should work. For example trap "ls -lh /" INT will cause Ctrl+C in your shell to result in ls -lh / (program with 2 args) being called.

like image 35
Michał Kosmulski Avatar answered Sep 30 '22 20:09

Michał Kosmulski