So I am trying to tell if the machine has a battery, then run different commands based on whether or not it does. Here's what I have so far:

upower -d >> /tmp/batstat
if [ grep -F BAT0 /tmp/batstat ]; then
    echo "BAT0 PRESENT" >> /tmp/batstat
    echo "NO BAT0" >> /tmp/batstat

However, this returns the error "bash: [: too many arguments" while writing NO BAT0 to /tmp/batstat as expected. Running only the grep works properly, so I don't understand why it doesn't work as an if condition.

If there is a better way to check for a battery, I am 100% open to it.

  • [ is interpreting grep -F BAT0 /tmp/batstat as four separate arguments, not the one or two it's expecting. I'm sure there are more idiomatic ways to do it, but I'd do it like so: [ "$(grep -F 'text' test.txt)" != "" ]. Not an answer, because unsure about battery: what OS are you running? – John N Dec 15 '16 at 19:01
  • I'm using Debian Jessie. – user5104897 Dec 15 '16 at 19:31
  • Also, when I try using your recommendation with BAT0 in place of text (with or without single quotes), I get the following error: bash: $'NO BAT0\nNO BAT0\nNO BAT0\nNO BAT0\nNO BAT0\nNO BAT0': command not found – user5104897 Dec 15 '16 at 19:36
if upower -d | grep -qF BAT0 ; then
   echo "BAT0 PRESENT"
   echo "NO BAT0"

if will take a series of commands and works on the status of the final one, in this case the grep. grep returns true if it matches, and false otherwise.


grep -F BAT0 /tmp/batstat is in no way a CONDITIONAL EXPRESSION (as detailed in the fine manual) for the test builtin of bash. Since the output of grep is unused, the -q option and relying on the exit code likely suffices.

grep -F -q BAT0 batstat
if [[ $? -eq 0 ]]; then
    echo yea
    echo nay

Also, /tmp/batstat is likely a very poor choice, especially where a nefarious local user has access. Consider instead using mktemp(1), or not locating the file under /tmp.

  • I didn't include this in the post but the script immediately does rm /tmp/batstat as soon as it is finished with the commands in the if statement. I only need to check if upower -d mentions BAT0 for this one if statement. This is for a Debian preseed installer so I'm not sure where else to write to. – user5104897 Dec 15 '16 at 19:43
  • I am thinking of using something like this: d-i upower -d >> /tmp/batstat d-i grep -F -q BAT0 /tmp/batstat d-i if [[ $? -eq 0 ]]; then echo yea else echo nay fi d-i rm /tmp/batstat – user5104897 Dec 15 '16 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.