Bash Script Not Executing in Cron Correctly

后端 未结 3 593
北荒
北荒 2020-12-22 07:47

So, I have a bash script that should pipe the output of ifconfig to a text file on the hour, every hour. As many people seem to have encountered, this script does not funct

3条回答
  •  青春惊慌失措
    2020-12-22 08:22

    Your script should have a "shebang" line at the top:

    #!/bin/sh
    

    though it's not absolutely required.

    The script overwrites ip.txt because you told it to. That's what the > redirection operator does. If you want to append to the end of the file, use >>. (You said you tried that, with identical results. I doubt that that's true. I suspect the cron job just isn't producing any output, so it's appending nothing to the file.)

    But you don't need a separate script just to do the redirection; you can use > or >> in the cron job itself:

    0 * * * *    ifconfig >> /home/drake/Dropbox/maintenance_scripts/ip.txt
    

    And at least on my system, the default $PATH for cron jobs is /usr/bin:/bin, but ifconfig is /sbin/ifconfig. Try which ifconfig or type ifconfig to see where ifconfig lives on your system (we're both using Ubuntu, so it's probably the same), and use the full path in the cron job; for example:

    0 * * * *    /sbin/ifconfig >> /home/drake/Dropbox/maintenance_scripts/ip.txt
    

    And if you want to see when the output changed (I presume that's what you're checking for), it's easy enough to add a timestamp:

    0 * * * *    ( date ; /sbin/ifconfig ) >> /home/drake/Dropbox/maintenance_scripts/ip.txt
    

提交回复
热议问题