I often use bash
shell scripts to run simple commands for many different files. For example, suppose that I have the following bash
shell script, called script.sh
, that runs the program/command foo
on three text files "a.txt"
, "b.txt"
, "c.txt"
:
#!/bin/bash
for strname in "a" "b" "c"
do
foo $strname".txt"
done
Also, suppose that foo $strname".txt"
is slow, so the execution of the script will take a long time (hours or days, for example). Because of this, I would like to use nohup
so that the execution continues even if the terminal is closed or disconnected. I would also like the script to immediately go to the background, so I will use the &
operator. Thus I will use the following command to call script.sh
:
nohup bash script.sh &
This works fine for running the script in the background and without hangup, but now suppose that I would like to terminate the execution at some point for some reason. How can I do this?
The problem that I have encountered is that, by looking at top
, I see only the foo
corresponding to "a.txt"
. I can terminate that foo
call, but then the foo
corresponding to "b.txt"
gets called and then I have to terminate that one as well, and so on. For tens or hundreds of text files specified in the for
loop, it becomes a pain to terminate every foo
, one by one! So somehow I need to instead terminate the shell script itself, not the particular calls issued from the shell script.
When I type the command
ps -u myusername
where myusername
is my username, I get a list of processes that I'm running. But I see two different process IDs called bash
. How do I know which of these processes, if any, corresponds to my original call nohup bash script.sh &
?
for s in a b c; do foo "$s".txt; done
nohup
will be long gone by the time you bring up a process listing to see the job you started. You can look at the "niceness" column in theps
output but the answers here are more useful.