Search code examples
bashsleepnohup

Script bash always running


I want to create a simple bash script that prints a text every 5 minutes. Script will be launched at the boot.

#!/bin/bash
while true ; do
echo "You received a new mail"
sleep 300
done

I tried to use nohup like this

nohup script.sh 

But the output is redirected to nohup.out, I don't want it and the process is not executed in background, it's working until I leave with ctrl+C


Solution

  • You can easily redirect stdout/stderr however you want by running:

    nohup script.sh > someotherfile.
    

    The point of nohup that it will continue to run when the shell closes, but it doesn't immediately get sent to the background. If you want it to:

    nohup script.sh > someotherfile &
    

    If you forget the & the usual ctrl-z followed by bg works. In any case if you close the shell/terminal it will continue running. Here's a quick tutorial: http://linux.101hacks.com/unix/nohup-command/.

    If you want to lookup other options check setsid, and also crontab. That last one is a bit more flexible in terms of when to run and auto-starting. Here's a first good reference:

    https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job#2369