Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash nohup with two commands

Tags:

bash

sh

nohup

I have a small function in my bashrc so I can run a script and have the ouput sent to my email when it finishes. The code is the following:

run() {
    [email protected]
    last="${!#}"
    rest="${@:1:($#-1)}"

    (nohup $rest &> $last < /dev/null; mail -s "$rest" "$email" < "$last") &
}

The function is used like this

run ./script.sh arg1 arg2 output

and it seems to be working most of the time, but sometimes the email does not get sent even though the script finished. I suspect it has to do with me closing the server terminal. In those cases, the script is still running because of the nohup but it does not send the email at the end. I'd really appreciate some pointers in order to get it working properly.

like image 927
skd Avatar asked Feb 10 '14 15:02

skd


Video Answer


1 Answers

There are multiple ways to resolve this, but I think I would recommend this:

run() {
  [email protected]
  rest="${@:1:($#-1)}"

  nohup bash -c "$rest < /dev/null 2>&1 | mail -s \"$rest\" \"$email\"" &
}

The issue is your nohup command ended at the semicolon after /dev/null and thus didn't apply to the mail part. The ( ... ) introduces a subshell, but is not an external command, so nohup ( ... ) wouldn't work, which is why bash -c "..." is required (you could also use ${SHELL} -c " ..." for added portability if that's important). The double quotes you had need to be escaped when enclosed in another set of quotes. Also, the temporary file is not necessary (unless you wanted to keep it around for some reason - if that's the case, feel free to put the redirections back and separate the commands with ; instead of |). Without needing the output file, you could also dispense with the rest=... bit and just call it as run script.sh arg1 arg2, but if you already have calls to it spread throughout other code, it might be simpler to leave that bit in - you'll have to figure that part out...

like image 176
twalberg Avatar answered Nov 04 '22 06:11

twalberg