Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different results between crontab and running script manually

I have a bash script that does this:

nmap -sn 192.168.0.1-255 | grep -Eo 192.168.0.{1,3\}[0-9] > new.txt
date >> network_log
echo ---------------------------- >> network_log
cat new.txt >> network_log

Scans the network, and appends results to file network_log with a timestamp. After running it manually, the network_log file looks like this:

Tue 13 Sep 2016 11:22:23 EDT 
---------------------------- 

192.168.0.1
192.168.0.2 
192.168.0.45

whereas the cronjobs produce the following outputs in my network_log file:

Tue Sep 13 17:46:00 EDT 2016
----------------------------

with no ip results. Note: the cronjob is running from root user so it has all the elevation it needs to scan the entire network.

like image 885
carrots Avatar asked Oct 28 '25 07:10

carrots


1 Answers

Your script lacks a shebang, so it might run with different shells depending on a crontab or manual launch.

Add the following as first line in your script (replace bash with your current user shell if needed):

#!/usr/bin/env bash

Don't use /bin/bash as it's less portable than /usr/bin/env bash.

Also, crontab runs won't have the PATH variable. Print your path variable with:

echo $PATH

And add it as second line of your script like:

#!/usr/bin/env bash
PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin

This should ensure that your script runs in the same environment when run by crontab or manually.

like image 123
Orsiris de Jong Avatar answered Oct 29 '25 23:10

Orsiris de Jong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!