Search code examples
linuxmacosshellcron

Basic Cron job to run a shell script to append date in a log, not working


I have a addlog.sh file which has the following content:

echo "time right now:" `date` >> ~/Desktop/date.log

This is how my crontab -l looks like:

* * * * * /bin/sh /Users/naman/Desktop/addlog.sh

I have added correct permissions to addlog.sh file and my shell is at /bin/sh. I have verified that the manual run of addlog.sh is appending time to the date.log file.

I am running this in my local Mac. But its not working and not sure what I might be missing here.


Solution

  • I suspect you are running Catalina (10.15) with its restrictive system integrity protection. There are two possible solutions.

    Solution 1

    Move your script and log file out of ~/Desktop into ~/. In contrast to ~/Desktop, ~/Documents, and may other folders, the home directory is not subject to system integrity protection.

    Solution 2

    If you need to keep your script and logfile under ~/Desktop:

    1. Add #!/bin/sh shebang (first line) to your addlog.sh script
    2. Make a trivial addlog.app from your addlog.sh script as follows:
    mkdir -p ~/Desktop/addlog.app/Resources/MacOS/
    cp ~/Desktop/addlog.sh ~/Desktop/addlog.app/Resources/MacOS/addlog
    chmod +x ~/Desktop/addlog.app/Resources/MacOS/addlog
    
    1. Change your crontab to the following:
    * * * * * /Users/naman/Desktop/addlog.app/Resources/MacOS/addlog
    

    You also have to allow the newly created app access to files in SIP-protected areas, as follows:

    1. Open 'System Preferences', 'Security & Privacy'
    2. Click on the padlock and authenticate to make changes.
    3. Select 'Full Disk Access' in the left pane.
    4. On the right-hand side click +.
    5. Navigate to Desktop and select your new app addlog. It will be added to the list of apps. Ensure that the checkmark is selected.
    6. Close 'System Preferences'