George Kastrinis
George Kastrinis

Reputation: 5172

How to run "independent" commands in script

I have a series of "commands" (calls to bash shell functions really) that compute some statistics. Each command is irrelevant in general from all others, and some might take more time than wanted, sometimes.

So far, I have a bash script that calls those command, the one after the other. If some command takes too much time, and I ctrl+C it, the whole script dies (as expected). I found that if I call them inside parenthesis (which forks the shell), like ( command1 ) ; ( command2 ) and I ctrl+C while command1 is running, then command2 will run without problem afterwards.

The above applies, when I try it directly in the terminal. But if I do that inside a script, it doesn't work. I guess the ctrl+C goes to the whole script, and terminates that.

Is there any way I can accomplice what I want? Usage of bash shell is not so strict, so I'm happy with a solution say in python for example, though one in bash is preferred.

Edit: I want to be able somehow to "cancel" some command, and the rest to execute afterwards (one at a time) with no problem. Not to run the commands in parallel.

Upvotes: 2

Views: 1459

Answers (2)

William Pursell
William Pursell

Reputation: 212248

What you want should work if you simply trap SIGINT. For example:

#!/bin/sh

trap : 2

cmd1
cmd2
cmd3

When you hit ^C, it will send SIGINT to the shell script and the currently running process (cmd1,cmd2. or cmd3). The cmd will die, and the shell script will start the next cmd.

Upvotes: 3

Related Questions