0

Using blueutil to try to connect or disconnect my headphones, when you test using the --is-connected it returns either a 0 or 1. I want to use that to either connect or disconnect the headphones, but I keep getting a "0: command not found" error.

blueutil --is-connected ac-90-85-3e-0d-04
if $? -eq 0
  then
    blueutil --connect ac-90-85-3e-0d-04
  else
    blueutil --disconnect ac-90-85-3e-0d-04
fi
Matt Klaver
  • 169
  • 1
  • 10
  • Try to set like this EXIT_STATUS=$? and then if $EXIT_STATUS -eq 0 – rootkonda Feb 17 '20 at 21:52
  • @rootkonda, that has the same problem the OP's original code does -- it's trying to run `$EXIT_STATUS` as a command, which it isn't (even when passed `-eq` as its first argument and `0` as its second). – Charles Duffy Feb 17 '20 at 22:03
  • Related: [Why is testing `$?` to see if a command succeeded or not an antipattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – Charles Duffy Feb 17 '20 at 22:04
  • But thats how we refer shell variables right ? $variable_name. Atleast this should work if $EXIT_STATUS = 0 – rootkonda Feb 17 '20 at 22:10
  • @rootkonda This has nothing to do with the variable being used, but the fact that `$? -eq 0` isn't a valid *command*. `?` is a perfectly valid *parameter* name (a variable being a particular kind of parameter in `bash`). – chepner Feb 17 '20 at 22:38

1 Answers1

4

The shell doesn't do comparisons by itself; that's the job of the test command:

if test $? -eq 0

though all if does is look at the exit status of its condition list; you can call blueutil directly from that list.

if blueutil --is-connected ac-90-85-3e-0d-04
  then
    blueutil --connect ac-90-85-3e-0d-04
  else
    blueutil --disconnect ac-90-85-3e-0d-04
fi
chepner
  • 497,756
  • 71
  • 530
  • 681