macOS - shells scripts manually runs but not when automated

Trying to automated running this shell script and getting the results.

So I have a shell script:

backup.sh -- finds latest backup time machine backup date, creates a file on the desktop called bkDate.txt then added the date into the file.

#!/bin/sh
enabled=`/usr/bin/defaults read /Library/Preferences/com.apple.TimeMachine AutoBackup`
if [ "$enabled" == "1" ];then
lastBackupTimestamp=`date -j -f "%a %b %d %T %Z %Y" "$(/usr/libexec/PlistBuddy -c "Print Destinations:0:SnapshotDates" /Library/Preferences/com.apple.TimeMachine.plist | tail -n 2 | head -n 1 | awk '{$1=$1};1')" "+%Y-%m-%d %H:%M:%S"`
echo "$lastBackupTimestamp"
else
echo "<result>Disabled</result>"
fi
echo "$lastBackupTimestamp" > ~/Desktop/bkDate.txt
  • If I run it manually through sh ~/Desktop/backup.sh it works
  • if I use automator (shell or AppleScript) or crontab. It produces the file but the contents is empty.

Trying to figure out why it's not letting me automate it and how would can I automate the file and output?

Doing this with crontab is going to be tricky because that runs the code in a daemon context and you really need the code to run in a user context.

Doing it with Automator should work. My advice is that you add log points to the script to find out where things are going wrong.

Also, try putting the file somewhere other then the desktop. The desktop is protected by MAC (see On File System Permissions) and that can cause problems for scripts.

ps Reading undocumented properties from system preferences files is not the path to long-term binary compatibility. This sort of thing is fine for a script that you only run locally — you just have to be prepared to deal with it breaking in the future — but do not build a product that relies on it.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

macOS - shells scripts manually runs but not when automated
 
 
Q