Reputation:
I have a simple script, that works fine in the terminal, but not in init.d scripts or crontab. I'm working on a raspberry pi.
Is there a rule to writing scripts that run in the background?
This is my script:
#!/bin/bash
while true; do echo "ALIVE" | sudo nc -l -p 80; done
Upvotes: 0
Views: 460
Reputation: 4681
Cron scripts defined in /etc/crontab
, /etc/cron.d
or via
crontab -e
may run as a user other than root
. All permissions
(e.g. on logfiles) and authorization information (in your case sudoers
) must be set
accordingly.
If they do not contain a Shebang line, cron scripts may run in a different shell, depending on the user the script is running as (see the shell set in /etc/passwd
). The shell can also be overridden via SHELL
variable in a crontab. This is not relevant for the OP's script.
The shell running init.d
and cron
scripts may be using a different
environment. Most notably the PATH
may be different, so it is recommended to use absolute paths only or set the PATH
as needed.
Upvotes: 1
Reputation: 6723
The user running the script must be able to sudo. Configure this with the visudo
command.
You should check for output/errors. You can do that by changing it to:
while true; do echo "ALIVE" | sudo nc -l -p 80 &>/var/log/netcat-test.log; done
Note that you should write the log to a place where that user definitely has access, and a directory that already exists. But this will trash your disk, due to writing lots and lots of logs. I suggest adding a delay:
while true; do echo "ALIVE" | sudo nc -l -p 80 &>>/var/log/netcat-test.log; sleep 30; done
echo Script started >> the-log-file; date >> the-log-file
. If the script is not starting, make sure it is marked as executable. If the script IS starting, make sure the script is not causing the system to crash--does the system need this script to return? Because it is not currently a background daemon. It does not ever finish, nor does it return control to the shell. Try replacing while true
with for count in 1 2
for testing, to execute just twice.Upvotes: 0