문제

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=example@gmail.com
    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.

도움이 되었습니까?

해결책

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

run() {
  email=example@gmail.com
  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...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top