简体   繁体   中英

crontab doesn't execute 'ioreg' on my mac

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 doesn't work in the crontab? 在crontab中不起作用? Please tell me what happen if anybody knows my problem.

thanks.

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... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM