If I were writing the script for Linux, I'd have it look through /proc/acpi/ to check the state of the battery. There's no /proc in OS X. There is, however, a power management command, pmset.
If I run pmset -g while on AC, I get:
Currently drawing from 'AC Power'
-InternalBattery-0 100%; AC attached; not charging
If I run it while on battery, I get:
Currently drawing from 'Battery Power'
-InternalBattery-0 100%; discharging; (no estimate)
I simply have my script grep the output from pmset for "discharging":
if $PMSET -g batt | $GREP -q discharging;
See the pmset(1) manpage for more info.