crontab doesn't execute 'ioreg' on my mac

可紊 提交于 2019-12-11 03:08:54

问题


I would like track my battery information on my mac, So I assign a script file to crontab but it doesn't work.

#!/bin/bash
#getbattery.sh
CURRENT_CAPACITY=$(ioreg -l -n AppleSmartBattery -r | grep CurrentCapacity | awk '{print $3}')
MAX_CAPACITY=$(ioreg -l -n AppleSmartBattery -r | grep MaxCapacity | awk '{print $3}')
CHARGE=$(echo $CURRENT_CAPACITY $MAX_CAPACITY | awk '{printf ("%i", $1/$2 * 100)}')
echo "$CHARGE""%  $(date) "

-

#my crontab content:
*/1 * * * * ~/getbattery.sh >> ~/batteryinfo.txt

Why ioreg doesn't work in the crontab? Please tell me what happen if anybody knows my problem.

thanks.


回答1:


cron jobs run with a very minimal environment, including a very basic PATH (just /usr/bin:/bin). But ioreg is in /usr/sbin, so it won't be found as a command based on that PATH. There are three easy solutions:

  1. Set the PATH in your crontab:

    PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
    */1 * * * * ~/getbattery.sh >> ~/batteryinfo.txt
    
  2. Set the PATH in your script:

    #!/bin/bash
    #getbattery.sh
    PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
    CURRENT_CAPACITY=$(ioreg -l -n AppleSmartBattery -r | grep CurrentCapacity | awk '{print $3}')
    # etc...
    
  3. Use an explicit path for ioreg (and any other commands not in /bin or /usr/bin) in your script :

    #!/bin/bash
    #getbattery.sh
    CURRENT_CAPACITY=$(/usr/sbin/ioreg -l -n AppleSmartBattery -r | grep CurrentCapacity | awk '{print $3}')
    # etc...
    


来源:https://stackoverflow.com/questions/25622613/crontab-doesnt-execute-ioreg-on-my-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!