Kusalananda gave tips on how to improve the code, but didn't exactly explain what you did wrong. Let's go over that:
I tried something like ret=$?
and then if [$ret -ne 0]
but I kept getting the else statement happen, even if ret is 1.
[
is a command, so you need to put a space between the command and its arguments, else the argument is going to be understood to be part of the command name. If ret
is set to 1
, bash should output the error [1: command not found
, and if
should see falsy because of the error. Similarly, [
requires the last argument to be ]
, and 0]
isn't that. You also need a space there.
What you wanted was:
if [ "$ret" -ne 0 ]
Next part:
ret=bluetoothctl connect 26:EE:F1:58:92:AF | grep "connection successful"
What you're doing here is running the pipe connect 26:EE:F1:58:92:AF | grep "connection successful"
, while providing the connect
command (which probably doesn't exist) the environment variable ret
with value bluetoothctl
.
In order to collect its output, you need to enclose the command in $()
:
ret="$(bluetoothctl connect 26:EE:F1:58:92:AF | grep "connection successful")"
About this:
if [$ret -ne ""]; then
You have the same issue of lacking spaces, but something further to understand is that basically most things are strings implicitly in bash, quotes are mostly just a way to be more explicit about it (besides also controlling some details on expansions). That means that [$ret -ne ""]
evaluates pretty much exactly the same as the followings:
[$ret -ne ]
[$ret -ne ""''""'']
"["$ret "-ne" """]"
"["$ret"" "-ne""""" """]"""
which with $ret
being empty, would equate to [ -ne ]
. That evaluates to truthy because with just one argument (ignoring ]
), [
checks whether it's a non-empty string, and -ne
is.
Were $ret
to be something else like foo bar baz
, it'd be word-split because of the lack of quotes and you'd get the command [foo bar baz -ne ]
, which would have 4 arguments (including ]
) and be falsy because bash wouldn't find the command [foo
. Had you quoted $ret
like ["$ret" -ne ""]
, then you'd get the equivalent of "[foo bar baz" -ne ]
, which would have 2 arguments (including ]
) and also be falsy because bash wouldn't find the command [foo bar baz
.
Another mistake you did here was using -ne
, which is exclusively for numeric comparison. Even if you fixed the spacing and quoting issue, bash would give you the error integer expression expected
. What you wanted was !=
, which is for string comparison.
To sum it up and fix all that, what you wanted here was:
if [ "$ret" != "" ]; then
which can also be written as
if [ -n "$ret" ]; then
or
if [ "$ret" ]; then
[
and]
. Remember,[
is just an ordinary command, not shell syntax, so you need to separate it from its arguments with a space.[$ret
would be likeecho$ret
.until
keyword.