Trap function by passing arguments?

I searched everywhere and I came to the conclusion that there is no way to do this other than global variables, but I believe that a guru at stackoverflow.com can help me:

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

+7
source share
3 answers

trap allows you to specify an arbitrary command (or sequence of commands), but you must pass this 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 a SIGINT. In your case, it sounds the way you want:

 trap '<function> <arg_1> <arg_2>' SIGINT 
+13
source

I may not understand you, but ... this is legal:

 trap "cp /etc/passwd $HOME/p" SIGINT trap 'cp /etc/passwd /tmp/p; echo wooo hoo' SIGINT 
+2
source

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

+1
source

All Articles