【完全版】Macターミナルでバッテリー情報を確認する方法|残量・最大容量・サイクル数を詳細表示

Mac

Macを長く使っていると、「最近バッテリーの持ちが悪いな」「充電サイクル数はどのくらいだろう?」と気になることがありませんか?

システム環境設定から確認することもできますが、ターミナルを使えばより詳細な情報を素早く取得できます。

この記事では、Macのターミナルでバッテリー情報を確認する様々な方法を詳しく解説します。

スポンサーリンク

バッテリー情報の基本知識

Macバッテリーの重要な指標

まず、バッテリー管理で知っておくべき主要な指標を理解しましょう。

指標説明正常な範囲確認の重要度
現在の残量現在の充電レベル(%)0-100%日常的
現在容量実際に利用可能な容量(mAh)定期的
最大容量バッテリーが保持できる最大容量定期的
設計容量工場出荷時の設計容量比較基準
サイクル数充放電を繰り返した回数<1000回重要
状態バッテリーの健康状態Normal重要
温度バッテリーの現在温度0-35℃監視推奨

バッテリー劣化の判断基準

サイクル数による判断

  • 0-300回:新品に近い状態
  • 300-600回:軽度の劣化
  • 600-1000回:中程度の劣化
  • 1000回以上:交換検討時期

容量による判断

バッテリー健康度 = (現在の最大容量 / 設計容量) × 100%

90%以上:良好
80-90%:やや劣化
70-80%:劣化が進行
70%未満:交換推奨

なぜターミナルで確認するのか

メリット

  • 詳細情報:GUIでは見られない詳細データを取得
  • 自動化:スクリプトで定期監視が可能
  • 高速性:コマンド一発で必要な情報を表示
  • リモート監視:SSH経由でも確認可能
  • ログ化:データを記録して推移を分析

バッテリーの基本を理解したところで、実際のコマンドを使った確認方法を見ていきましょう。

ioregを使った基本的なバッテリー情報取得

基本コマンドと出力内容

基本的なバッテリー情報の取得

ioreg -l | grep -e "CurrentCapacity" -e "MaxCapacity" -e "CycleCount"

実行例

   | |           "AppleRawCurrentCapacity" = 4174
    | |           "AppleRawMaxCapacity" = 4273
    | |           "MaxCapacity" = 4273
    | |           "DesignCycleCount70" = 248
    | |           "CurrentCapacity" = 4174
    | |           "CycleCount" = 159

出力の詳細解説

項目意味単位説明
CurrentCapacity現在の充電量mAh現在バッテリーに蓄えられている電力量
MaxCapacity現在の最大容量mAhバッテリーが現在保持できる最大電力量
CycleCountサイクル数充放電を繰り返した累計回数

より詳細な情報の取得

全バッテリー情報の詳細表示

ioreg -l -w0 | grep -A20 "AppleSmartBattery"

設計容量も含めた包括的な情報

ioreg -l | grep -e "CurrentCapacity" -e "MaxCapacity" -e "DesignCapacity" -e "CycleCount" -e "Temperature"

実行例

"CurrentCapacity" = 4947
"MaxCapacity" = 5103
"DesignCapacity" = 5300
"CycleCount" = 342
"Temperature" = 3034

温度の換算

# 温度をセルシウスに変換(Temperatureの値を100で割る)
ioreg -l | grep "Temperature" | awk '{print "Temperature: " ($3/100) "°C"}'

特定の情報のみを抽出

現在の充電レベル(%)を計算

# 現在容量 / 最大容量 × 100 を計算
ioreg -l | awk '
/CurrentCapacity/ { current = $3 }
/MaxCapacity/ { max = $3 }
END { if (max > 0) printf "Current Battery Level: %.1f%%\n", (current/max)*100 }'

バッテリー健康度の計算

# 最大容量 / 設計容量 × 100 を計算
ioreg -l | awk '
/MaxCapacity/ { max = $3 }
/DesignCapacity/ { design = $3 }
END { if (design > 0) printf "Battery Health: %.1f%%\n", (max/design)*100 }'

サイクル数のみを抽出

ioreg -l | grep "CycleCount" | awk '{print "Cycle Count: " $3}'

エラー処理を含む安全なスクリプト

#!/bin/bash

# バッテリー情報の安全な取得
get_battery_info() {
    local ioreg_output=$(ioreg -l 2>/dev/null)
    
    if [[ -z "$ioreg_output" ]]; then
        echo "Error: Unable to retrieve battery information"
        return 1
    fi
    
    local current=$(echo "$ioreg_output" | grep "CurrentCapacity" | awk '{print $3}')
    local max=$(echo "$ioreg_output" | grep "MaxCapacity" | awk '{print $3}')
    local design=$(echo "$ioreg_output" | grep "DesignCapacity" | awk '{print $3}')
    local cycles=$(echo "$ioreg_output" | grep "CycleCount" | awk '{print $3}')
    
    if [[ -n "$current" && -n "$max" && -n "$design" && -n "$cycles" ]]; then
        local level=$(echo "scale=1; ($current/$max)*100" | bc -l)
        local health=$(echo "scale=1; ($max/$design)*100" | bc -l)
        
        echo "=== Battery Information ==="
        echo "Current Level: ${level}%"
        echo "Battery Health: ${health}%"
        echo "Cycle Count: ${cycles}"
        echo "Current Capacity: ${current} mAh"
        echo "Max Capacity: ${max} mAh"
        echo "Design Capacity: ${design} mAh"
    else
        echo "Error: Some battery information could not be retrieved"
        return 1
    fi
}

get_battery_info

ioregコマンドは最も詳細な情報を提供しますが、出力が少し複雑です。次は、より人間に優しい形式で情報を表示するsystem_profilerを見ていきましょう。

system_profilerを使った詳細確認

基本的な使用方法

バッテリーの詳細情報表示

system_profiler SPPowerDataType

実行例

Power:

      Battery Information:

          Model Information:
              Serial Number: D86748501J3F2A1AE
              Manufacturer: DP
              Device Name: bq20z651
              Pack Lot Code: 0
              PCB Lot Code: 0
              Firmware Version: 201
              Hardware Revision: 000a
              Cell Revision: 158

          Charge Information:
              Charge Remaining (mAh): 4947
              Fully Charged: No
              Charging: No
              Full Charge Capacity (mAh): 5103

          Health Information:
              Cycle Count: 342
              Condition: Normal

          AC Charger Information:
              Connected: Yes
              ID: 0x0100
              Wattage (W): 61
              Family: 0xe000400a
              Revision: 0x0000
              Charging: No

特定情報の抽出

サイクル数のみを表示

system_profiler SPPowerDataType | grep "Cycle Count"

バッテリーの状態(Condition)を確認

system_profiler SPPowerDataType | grep "Condition"

出力例

              Condition: Normal

可能な状態値

  • Normal:正常
  • Replace Soon:まもなく交換
  • Replace Now:交換推奨
  • Service Recommended:サービス推奨

数値データの抽出と計算

充電容量の情報を抽出

system_profiler SPPowerDataType | grep -E "(Charge Remaining|Full Charge Capacity)" | awk '{print $NF}' | paste - -

バッテリー健康度の計算

#!/bin/bash

calculate_battery_health() {
    local profiler_output=$(system_profiler SPPowerDataType)
    
    local current_capacity=$(echo "$profiler_output" | grep "Full Charge Capacity" | awk '{print $(NF-1)}')
    local design_capacity=5300  # MacBook Proの一般的な設計容量(モデルにより異なる)
    
    if [[ -n "$current_capacity" && "$current_capacity" -gt 0 ]]; then
        local health=$(echo "scale=1; ($current_capacity/$design_capacity)*100" | bc -l)
        echo "Battery Health: ${health}%"
        echo "Current Max Capacity: ${current_capacity} mAh"
        echo "Design Capacity: ${design_capacity} mAh"
    else
        echo "Error: Could not retrieve capacity information"
    fi
}

calculate_battery_health

設計容量の自動取得

#!/bin/bash

get_design_capacity() {
    # ioregから設計容量を取得
    local design=$(ioreg -l | grep "DesignCapacity" | awk '{print $3}')
    echo "$design"
}

get_comprehensive_battery_info() {
    local profiler_output=$(system_profiler SPPowerDataType)
    local design_capacity=$(get_design_capacity)
    
    local current_capacity=$(echo "$profiler_output" | grep "Full Charge Capacity" | awk '{print $(NF-1)}')
    local cycle_count=$(echo "$profiler_output" | grep "Cycle Count" | awk '{print $3}')
    local condition=$(echo "$profiler_output" | grep "Condition" | awk '{print $2}')
    
    echo "=== Comprehensive Battery Information ==="
    echo "Condition: $condition"
    echo "Cycle Count: $cycle_count"
    echo "Current Max Capacity: $current_capacity mAh"
    echo "Design Capacity: $design_capacity mAh"
    
    if [[ -n "$current_capacity" && -n "$design_capacity" && "$design_capacity" -gt 0 ]]; then
        local health=$(echo "scale=1; ($current_capacity/$design_capacity)*100" | bc -l)
        echo "Battery Health: ${health}%"
    fi
}

get_comprehensive_battery_info

pmsetを使った現在状態の確認

基本的な状態確認

現在のバッテリー状態を表示

pmset -g batt

実行例

Now drawing from 'AC Power'
 -InternalBattery-0	81%; discharging; 2:34 remaining present: true

出力の詳細解説

  • 電源状態:’AC Power’(電源接続)または ‘Battery Power’(バッテリー駆動)
  • 充電レベル:81%(現在の充電残量)
  • 状態:discharging(放電中)、charging(充電中)、charged(充電完了)
  • 残り時間:2:34 remaining(推定残り時間)

バッテリー残量のみを抽出

数値のみを取得

pmset -g batt | grep -Eo "\d+%" | cut -d% -f1

実行例

81

より詳細な抽出スクリプト

#!/bin/bash

get_battery_status() {
    local batt_info=$(pmset -g batt | head -2 | tail -1)
    
    # 各情報を抽出
    local percentage=$(echo "$batt_info" | grep -Eo "\d+%" | head -1)
    local status=$(echo "$batt_info" | sed 's/.*; \([^;]*\); .*/\1/')
    local time_remaining=$(echo "$batt_info" | sed 's/.*; \([^;]*\) remaining.*/\1/' | tail -1)
    local power_source=$(pmset -g batt | head -1 | sed "s/Now drawing from '\(.*\)'/\1/")
    
    echo "=== Current Battery Status ==="
    echo "Power Source: $power_source"
    echo "Battery Level: $percentage"
    echo "Status: $status"
    echo "Time Remaining: $time_remaining"
}

get_battery_status

詳細な電源情報

すべての電源設定を表示

pmset -g

実行例

System-wide power settings:
Currently in use:
 standby              1
 Sleep On Power Button 1
 hibernatefile        /var/vm/sleepimage
 networkoversleep     0
 disksleep            10
 sleep                1
 autopoweroffdelay    28800
 hibernatemode        3
 autopoweroff         1
 ttyskeepawake        1
 displaysleep         2
 tcpkeepalive         1
 lowpowermode         0

アクティブなプロファイルの確認

pmset -g custom

電源アダプターの情報

接続されている電源アダプターの詳細

pmset -g adapter

実行例

Adapter Power:
 AdapterID            0x0100
 Watts                61W
 Revision             0x0000
 Family               0xe000400a
 SerialNumber         0x00000000
 Charging             No

バッテリー温度の監視

#!/bin/bash

monitor_battery_temp() {
    while true; do
        local temp_raw=$(ioreg -l | grep "Temperature" | awk '{print $3}')
        if [[ -n "$temp_raw" ]]; then
            local temp_celsius=$(echo "scale=1; $temp_raw/100" | bc -l)
            local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
            
            echo "[$timestamp] Battery Temperature: ${temp_celsius}°C"
            
            # 温度が高すぎる場合の警告
            if (( $(echo "$temp_celsius > 45" | bc -l) )); then
                echo "⚠️  WARNING: Battery temperature is high!"
            fi
        fi
        
        sleep 30  # 30秒間隔で監視
    done
}

# 使用方法: monitor_battery_temp

応用例とスクリプト活用

総合バッテリー情報スクリプト

包括的なバッテリー状況表示

#!/bin/bash

# バッテリー情報総合表示スクリプト
# 使用方法: ./battery_info.sh

show_battery_info() {
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    BATTERY INFORMATION                       ║"
    echo "╠══════════════════════════════════════════════════════════════╣"
    
    # 現在の状態(pmset)
    local pmset_info=$(pmset -g batt)
    local power_source=$(echo "$pmset_info" | head -1 | sed "s/Now drawing from '\(.*\)'/\1/")
    local battery_line=$(echo "$pmset_info" | grep "InternalBattery")
    local percentage=$(echo "$battery_line" | grep -Eo "\d+%" | head -1)
    local status=$(echo "$battery_line" | awk -F'; ' '{print $2}')
    local time_info=$(echo "$battery_line" | awk -F'; ' '{print $3}' | sed 's/ present.*//')
    
    echo "║ Power Source: $power_source"
    echo "║ Current Level: $percentage"
    echo "║ Status: $status"
    echo "║ Time: $time_info"
    echo "║"
    
    # 詳細情報(ioreg)
    local ioreg_output=$(ioreg -l 2>/dev/null)
    local current_capacity=$(echo "$ioreg_output" | grep "CurrentCapacity" | awk '{print $3}')
    local max_capacity=$(echo "$ioreg_output" | grep "MaxCapacity" | awk '{print $3}')
    local design_capacity=$(echo "$ioreg_output" | grep "DesignCapacity" | awk '{print $3}')
    local cycle_count=$(echo "$ioreg_output" | grep "CycleCount" | awk '{print $3}')
    local temp_raw=$(echo "$ioreg_output" | grep "Temperature" | awk '{print $3}')
    
    # 計算
    if [[ -n "$current_capacity" && -n "$max_capacity" && -n "$design_capacity" ]]; then
        local exact_level=$(echo "scale=1; ($current_capacity/$max_capacity)*100" | bc -l)
        local health=$(echo "scale=1; ($max_capacity/$design_capacity)*100" | bc -l)
        local temp_celsius=$(echo "scale=1; $temp_raw/100" | bc -l)
        
        echo "║ Exact Level: ${exact_level}%"
        echo "║ Health: ${health}%"
        echo "║ Cycle Count: $cycle_count"
        echo "║ Temperature: ${temp_celsius}°C"
        echo "║"
        echo "║ Current Capacity: $current_capacity mAh"
        echo "║ Max Capacity: $max_capacity mAh"
        echo "║ Design Capacity: $design_capacity mAh"
    fi
    
    # 状態評価
    echo "║"
    echo "║ Status Assessment:"
    
    # サイクル数評価
    if [[ -n "$cycle_count" ]]; then
        if (( cycle_count < 300 )); then
            echo "║ 🟢 Cycle Count: Excellent ($cycle_count < 300)"
        elif (( cycle_count < 600 )); then
            echo "║ 🟡 Cycle Count: Good ($cycle_count < 600)"
        elif (( cycle_count < 1000 )); then
            echo "║ 🟠 Cycle Count: Fair ($cycle_count < 1000)"
        else
            echo "║ 🔴 Cycle Count: Consider replacement ($cycle_count ≥ 1000)"
        fi
    fi
    
    # 健康度評価
    if [[ -n "$health" ]]; then
        local health_num=$(echo "$health" | cut -d. -f1)
        if (( health_num >= 90 )); then
            echo "║ 🟢 Health: Excellent (${health}% ≥ 90%)"
        elif (( health_num >= 80 )); then
            echo "║ 🟡 Health: Good (${health}% ≥ 80%)"
        elif (( health_num >= 70 )); then
            echo "║ 🟠 Health: Fair (${health}% ≥ 70%)"
        else
            echo "║ 🔴 Health: Poor (${health}% < 70%)"
        fi
    fi
    
    # 温度評価
    if [[ -n "$temp_celsius" ]]; then
        local temp_num=$(echo "$temp_celsius" | cut -d. -f1)
        if (( temp_num < 35 )); then
            echo "║ 🟢 Temperature: Normal (${temp_celsius}°C < 35°C)"
        elif (( temp_num < 45 )); then
            echo "║ 🟡 Temperature: Warm (${temp_celsius}°C < 45°C)"
        else
            echo "║ 🔴 Temperature: Hot (${temp_celsius}°C ≥ 45°C)"
        fi
    fi
    
    echo "╚══════════════════════════════════════════════════════════════╝"
}

# システム情報確認
check_system_info() {
    echo "System: $(sw_vers -productName) $(sw_vers -productVersion)"
    echo "Model: $(system_profiler SPHardwareDataType | grep "Model Identifier" | awk '{print $3}')"
    echo "Timestamp: $(date)"
    echo ""
}

# メイン実行
main() {
    clear
    check_system_info
    show_battery_info
}

main

バッテリー監視とアラート

バッテリー低下時の自動アラート

#!/bin/bash

# バッテリー監視スクリプト
# 使用方法: ./battery_monitor.sh

BATTERY_LOW_THRESHOLD=20
BATTERY_CRITICAL_THRESHOLD=10
CHECK_INTERVAL=300  # 5分間隔

monitor_battery() {
    local log_file="$HOME/battery_monitor.log"
    
    echo "Battery monitoring started at $(date)" >> "$log_file"
    echo "Low threshold: $BATTERY_LOW_THRESHOLD%"
    echo "Critical threshold: $BATTERY_CRITICAL_THRESHOLD%"
    echo "Check interval: $CHECK_INTERVAL seconds"
    echo "Log file: $log_file"
    echo "Press Ctrl+C to stop monitoring"
    echo ""
    
    while true; do
        local battery_level=$(pmset -g batt | grep -Eo "\d+%" | cut -d% -f1)
        local power_source=$(pmset -g batt | head -1 | sed "s/Now drawing from '\(.*\)'/\1/")
        local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
        
        # ログ記録
        echo "[$timestamp] Battery: ${battery_level}%, Power: $power_source" >> "$log_file"
        
        # アラート判定
        if [[ "$power_source" == "Battery Power" ]]; then
            if (( battery_level <= BATTERY_CRITICAL_THRESHOLD )); then
                echo "🚨 CRITICAL: Battery at ${battery_level}%!"
                osascript -e "display notification \"Battery critically low: ${battery_level}%\" with title \"Battery Alert\" sound name \"Sosumi\""
                echo "[$timestamp] CRITICAL ALERT: Battery at ${battery_level}%" >> "$log_file"
            elif (( battery_level <= BATTERY_LOW_THRESHOLD )); then
                echo "⚠️  WARNING: Battery low at ${battery_level}%"
                osascript -e "display notification \"Battery low: ${battery_level}%\" with title \"Battery Warning\""
                echo "[$timestamp] LOW BATTERY WARNING: ${battery_level}%" >> "$log_file"
            fi
        fi
        
        echo "[$timestamp] Battery: ${battery_level}%, Power: $power_source"
        sleep $CHECK_INTERVAL
    done
}

monitor_battery

定期レポート生成

日次バッテリーレポート

#!/bin/bash

# 日次バッテリーレポート生成
# crontabで自動実行: 0 20 * * * /path/to/daily_battery_report.sh

generate_daily_report() {
    local report_file="$HOME/battery_reports/battery_report_$(date +%Y%m%d).txt"
    local report_dir="$HOME/battery_reports"
    
    # レポートディレクトリ作成
    mkdir -p "$report_dir"
    
    # レポート生成
    {
        echo "=================================="
        echo "DAILY BATTERY REPORT"
        echo "Date: $(date '+%Y-%m-%d %H:%M:%S')"
        echo "=================================="
        echo ""
        
        # 現在の状態
        echo "CURRENT STATUS:"
        pmset -g batt
        echo ""
        
        # 詳細情報
        echo "DETAILED INFORMATION:"
        local ioreg_output=$(ioreg -l)
        local current=$(echo "$ioreg_output" | grep "CurrentCapacity" | awk '{print $3}')
        local max=$(echo "$ioreg_output" | grep "MaxCapacity" | awk '{print $3}')
        local design=$(echo "$ioreg_output" | grep "DesignCapacity" | awk '{print $3}')
        local cycles=$(echo "$ioreg_output" | grep "CycleCount" | awk '{print $3}')
        local temp=$(echo "$ioreg_output" | grep "Temperature" | awk '{print $3/100}')
        
        echo "Current Capacity: $current mAh"
        echo "Max Capacity: $max mAh" 
        echo "Design Capacity: $design mAh"
        echo "Cycle Count: $cycles"
        echo "Temperature: ${temp}°C"
        
        if [[ -n "$max" && -n "$design" && "$design" -gt 0 ]]; then
            local health=$(echo "scale=1; ($max/$design)*100" | bc -l)
            echo "Battery Health: ${health}%"
        fi
        
        echo ""
        echo "SYSTEM INFO:"
        system_profiler SPPowerDataType | grep -A10 "Health Information"
        
    } > "$report_file"
    
    echo "Report generated: $report_file"
    
    # 古いレポートの削除(30日以上古いもの)
    find "$report_dir" -name "battery_report_*.txt" -mtime +30 -delete
}

generate_daily_report

CSV形式でのデータ出力

バッテリーデータのCSV出力

#!/bin/bash

# バッテリーデータをCSV形式で出力
# 使用方法: ./battery_to_csv.sh >> battery_data.csv

output_battery_csv() {
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    local ioreg_output=$(ioreg -l)
    local pmset_output=$(pmset -g batt)
    
    # データ取得
    local current_capacity=$(echo "$ioreg_output" | grep "CurrentCapacity" | awk '{print $3}')
    local max_capacity=$(echo "$ioreg_output" | grep "MaxCapacity" | awk '{print $3}')
    local design_capacity=$(echo "$ioreg_output" | grep "DesignCapacity" | awk '{print $3}')
    local cycle_count=$(echo "$ioreg_output" | grep "CycleCount" | awk '{print $3}')
    local temperature=$(echo "$ioreg_output" | grep "Temperature" | awk '{print $3/100}')
    local battery_percentage=$(echo "$pmset_output" | grep -Eo "\d+%" | cut -d% -f1)
    local power_source=$(echo "$pmset_output" | head -1 | sed "s/Now drawing from '\(.*\)'/\1/")
    local charging_status=$(echo "$pmset_output" | grep "InternalBattery" | awk -F'; ' '{print $2}')
    
    # ヘッダー出力(初回のみ)
    if [[ ! -f battery_data.csv ]]; then
        echo "Timestamp,Battery_Percentage,Current_Capacity,Max_Capacity,Design_Capacity,Cycle_Count,Temperature,Power_Source,Charging_Status"
    fi
    
    # データ出力
    echo "$timestamp,$battery_percentage,$current_capacity,$max_capacity,$design_capacity,$cycle_count,$temperature,$power_source,$charging_status"
}

# ヘッダーチェックして出力
if [[ "$1" == "--header" ]]; then
    echo "Timestamp,Battery_Percentage,Current_Capacity,Max_Capacity,Design_Capacity,Cycle_Count,Temperature,Power_Source,Charging_Status"
fi

output_battery_csv

トラブルシューティングとよくある問題

コマンドが動作しない場合

問題1:権限エラー

症状ioregsystem_profilerで情報が取得できない

対処方法

# 権限確認
whoami

# システム整合性保護の確認
csrutil status

# 診断レポートへのアクセス権限確認
ls -la /var/log/DiagnosticReports/

問題2:古いmacOSでの互換性

macOS Monterey以前での対応

# 古いバージョンでのバッテリー情報取得
ioreg -w0 -l | grep -E "(ExternalConnected|CurrentCapacity|MaxCapacity|CycleCount|DesignCapacity)"

# alternative方法
system_profiler SPPowerDataType | grep -E "(Cycle Count|Condition|Charge Remaining|Full Charge Capacity)"

問題3:M1/M2 Macでの特殊事項

Apple Silicon Macでの注意点

# M1/M2 Macでのバッテリー情報
# 一部の情報が異なる場合がある
ioreg -l -w0 | grep -i "battery" -A 20

# より確実な方法
system_profiler SPPowerDataType | grep -A 30 "Battery Information"

データが正確でない場合

バッテリー調整(キャリブレーション)

バッテリー調整の手順

  1. MacBookを100%まで充電
  2. 充電器を接続したまま2時間以上放置
  3. 充電器を外してバッテリーを完全に消耗
  4. 自動スリープした状態で5時間以上放置
  5. 再度100%まで充電

調整後の確認

#!/bin/bash
check_calibration() {
    echo "Checking battery calibration status..."
    
    local max_capacity=$(ioreg -l | grep "MaxCapacity" | awk '{print $3}')
    local design_capacity=$(ioreg -l | grep "DesignCapacity" | awk '{print $3}')
    
    if [[ -n "$max_capacity" && -n "$design_capacity" ]]; then
        local health=$(echo "scale=2; ($max_capacity/$design_capacity)*100" | bc -l)
        echo "Battery health after calibration: ${health}%"
        
        if (( $(echo "$health > 95" | bc -l) )); then
            echo "✅ Calibration successful"
        else
            echo "⚠️ Consider repeating calibration process"
        fi
    fi
}

check_calibration

自動化とシステム統合

launchdを使った定期実行

定期監視の設定

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.user.battery.monitor</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/bash</string>
        <string>/Users/username/Scripts/battery_monitor.sh</string>
    </array>
    <key>StartInterval</key>
    <integer>1800</integer>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/username/Logs/battery_monitor.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/username/Logs/battery_monitor_error.log</string>
</dict>
</plist>

設定方法

# plistファイルを作成
sudo nano ~/Library/LaunchAgents/com.user.battery.monitor.plist

# 権限設定
chmod 644 ~/Library/LaunchAgents/com.user.battery.monitor.plist

# 読み込み
launchctl load ~/Library/LaunchAgents/com.user.battery.monitor.plist

# 状態確認
launchctl list | grep battery

メール通知システム

バッテリー状態のメール通知

#!/bin/bash

# バッテリー状態のメール通知
# 使用前にmsmtpやmailの設定が必要

send_battery_alert() {
    local recipient="user@example.com"
    local smtp_server="smtp.gmail.com"
    local smtp_port="587"
    
    local battery_level=$(pmset -g batt | grep -Eo "\d+%" | cut -d% -f1)
    local cycle_count=$(ioreg -l | grep "CycleCount" | awk '{print $3}')
    local max_capacity=$(ioreg -l | grep "MaxCapacity" | awk '{print $3}')
    local design_capacity=$(ioreg -l | grep "DesignCapacity" | awk '{print $3}')
    
    if [[ -n "$max_capacity" && -n "$design_capacity" && "$design_capacity" -gt 0 ]]; then
        local health=$(echo "scale=1; ($max_capacity/$design_capacity)*100" | bc -l)
        
        # 条件チェック
        if (( battery_level <= 15 )) || (( cycle_count >= 1000 )) || (( $(echo "$health < 70" | bc -l) )); then
            local subject="Battery Alert - $(hostname)"
            local body="Battery Status Alert

Current Level: ${battery_level}%
Cycle Count: ${cycle_count}
Battery Health: ${health}%
Timestamp: $(date)

Please check your MacBook battery status."

            # メール送信(mailコマンド使用)
            echo "$body" | mail -s "$subject" "$recipient"
            
            echo "Alert email sent to $recipient"
        fi
    fi
}

send_battery_alert

Slack通知との連携

Slack Webhookを使った通知

#!/bin/bash

# Slack通知機能
SLACK_WEBHOOK_URL="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK"

send_slack_notification() {
    local message="$1"
    local color="$2"  # good, warning, danger
    
    local payload=$(cat <<EOF
{
    "attachments": [
        {
            "color": "$color",
            "title": "MacBook Battery Status",
            "text": "$message",
            "footer": "$(hostname)",
            "ts": $(date +%s)
        }
    ]
}
EOF
)

    curl -X POST -H 'Content-type: application/json' \
         --data "$payload" \
         "$SLACK_WEBHOOK_URL"
}

check_and_notify() {
    local battery_level=$(pmset -g batt | grep -Eo "\d+%" | cut -d% -f1)
    local cycle_count=$(ioreg -l | grep "CycleCount" | awk '{print $3}')
    local ioreg_output=$(ioreg -l)
    local max_capacity=$(echo "$ioreg_output" | grep "MaxCapacity" | awk '{print $3}')
    local design_capacity=$(echo "$ioreg_output" | grep "DesignCapacity" | awk '{print $3}')
    
    if [[ -n "$max_capacity" && -n "$design_capacity" && "$design_capacity" -gt 0 ]]; then
        local health=$(echo "scale=1; ($max_capacity/$design_capacity)*100" | bc -l)
        
        # 通知条件の判定
        if (( battery_level <= 10 )); then
            send_slack_notification "🚨 Battery critically low: ${battery_level}%" "danger"
        elif (( battery_level <= 20 )); then
            send_slack_notification "⚠️ Battery low: ${battery_level}%" "warning"
        elif (( cycle_count >= 1000 )); then
            send_slack_notification "🔄 High cycle count: ${cycle_count} cycles" "warning"
        elif (( $(echo "$health < 70" | bc -l) )); then
            send_slack_notification "🏥 Battery health degraded: ${health}%" "warning"
        fi
    fi
}

check_and_notify

パフォーマンス最適化とベストプラクティス

効率的なスクリプト作成

パフォーマンスを重視したバッテリー情報取得

#!/bin/bash

# 高速バッテリー情報取得
fast_battery_info() {
    # 一度だけioregを実行してキャッシュ
    local ioreg_cache=$(ioreg -l)
    
    # 必要な情報を一括抽出
    local battery_data=$(echo "$ioreg_cache" | grep -E "(CurrentCapacity|MaxCapacity|DesignCapacity|CycleCount|Temperature)" | awk '{print $1 " " $3}')
    
    # 連想配列に格納
    declare -A battery_info
    while read -r key value; do
        key=$(echo "$key" | tr -d '"')
        battery_info["$key"]="$value"
    done <<< "$battery_data"
    
    # 計算
    local current=${battery_info["CurrentCapacity"]}
    local max=${battery_info["MaxCapacity"]} 
    local design=${battery_info["DesignCapacity"]}
    local cycles=${battery_info["CycleCount"]}
    local temp_raw=${battery_info["Temperature"]}
    
    if [[ -n "$current" && -n "$max" && -n "$design" ]]; then
        local level=$(echo "scale=1; ($current/$max)*100" | bc -l)
        local health=$(echo "scale=1; ($max/$design)*100" | bc -l)
        local temp=$(echo "scale=1; $temp_raw/100" | bc -l)
        
        # 結果出力
        cat <<EOF
Level: ${level}%
Health: ${health}%
Cycles: ${cycles}
Temperature: ${temp}°C
Capacity: ${current}/${max}/${design} mAh
EOF
    fi
}

# 実行時間測定
time fast_battery_info

リソース使用量の最小化

軽量バッテリーモニター

#!/bin/bash

# 軽量バッテリーモニター
# CPU使用率を最小限に抑制

lightweight_monitor() {
    local cache_file="/tmp/battery_cache"
    local cache_duration=30  # 30秒間キャッシュを有効
    
    # キャッシュチェック
    if [[ -f "$cache_file" ]]; then
        local cache_age=$(($(date +%s) - $(stat -f %m "$cache_file")))
        if (( cache_age < cache_duration )); then
            cat "$cache_file"
            return
        fi
    fi
    
    # 新しいデータ取得
    local battery_level=$(pmset -g batt | grep -Eo "\d+%" | head -1)
    local power_source=$(pmset -g batt | head -1 | grep -o "'[^']*'" | tr -d "'")
    
    local output="Battery: $battery_level, Power: $power_source"
    
    # キャッシュに保存
    echo "$output" > "$cache_file"
    echo "$output"
}

lightweight_monitor

メモリ効率の最適化

大量データ処理時の最適化

#!/bin/bash

# メモリ効率を重視したログ分析
analyze_battery_logs() {
    local log_file="$1"
    local temp_dir="/tmp/battery_analysis_$"
    
    mkdir -p "$temp_dir"
    
    # ストリーミング処理でメモリ使用量を抑制
    {
        echo "Hour,Avg_Battery,Min_Battery,Max_Battery,Sample_Count"
        
        # 1時間ごとの統計を計算
        awk -F',' '
        NR > 1 {
            hour = substr($1, 12, 2)
            battery = $2
            
            if (battery in hours) {
                hours[hour]["sum"] += battery
                hours[hour]["count"]++
                if (battery < hours[hour]["min"]) hours[hour]["min"] = battery
                if (battery > hours[hour]["max"]) hours[hour]["max"] = battery
            } else {
                hours[hour]["sum"] = battery
                hours[hour]["count"] = 1
                hours[hour]["min"] = battery
                hours[hour]["max"] = battery
            }
        }
        END {
            for (h in hours) {
                avg = hours[h]["sum"] / hours[h]["count"]
                printf "%02d,%.1f,%d,%d,%d\n", h, avg, hours[h]["min"], hours[h]["max"], hours[h]["count"]
            }
        }' "$log_file" | sort -n
    }
    
    # 一時ディレクトリ削除
    rm -rf "$temp_dir"
}

# 使用例
# analyze_battery_logs "battery_data.csv" > battery_hourly_stats.csv

まとめ:バッテリー管理をマスターしてMacを長く使おう

Macのターミナルを使ったバッテリー管理は、単なる情報確認を超えて、システム全体の健康状態を把握し、最適化するための重要なスキルです。適切な監視と管理により、バッテリーの寿命を延ばし、Macのパフォーマンスを維持できます。

この記事で学んだポイント

  • 基本コマンド:ioreg、system_profiler、pmsetの使い分け
  • 詳細情報取得:容量、サイクル数、温度、健康度の総合的な把握
  • 自動化:スクリプトによる定期監視とアラート機能
  • 統合:メール、Slack、launchdとの連携
  • 最適化:パフォーマンスとリソース効率の両立

バッテリー管理のベストプラクティス

  • 定期監視:週次または月次での状態確認
  • 早期対応:劣化の兆候を見逃さない
  • 予防保全:適切な充電習慣とキャリブレーション
  • データ蓄積:長期的な傾向分析

コメント

タイトルとURLをコピーしました