1

I installed git bash on windows and try to write a few simple script. One thing I could not figure out so far is simple math and comparison. What I need is a random boolean currently:

#!/usr/bin/env bash

condition=$(($(($RANDOM%2)) == 1))

if $condition; then
    echo "a"
else
    echo "b"
fi

I got command not found. It looks like git bash is missing comparison operators, <,>,==,!=,-eq,-lt,-gt does not work no matter what I try. I found those in all of the examples. Any idea?

2
  • 1
    The operators aren't missing. The problem is just that the content of your condition variable is not a command, and if takes a command as the thing to check. (anubhava's answer enters an arithmetic context, in which you can use an arithmetic operation as a command; you could also do something like, say, if [ "$condition" -eq 1 ]; then, as [ is also a command). Commented Apr 1, 2020 at 22:31
  • 2
    There is no such thing as "git bash". Its name is Git for Windows and there is nothing special about it; it is a package that includes Git, Bash and a bunch of other standard Unix/Linux tools ported to Windows (on top of MinGW). Commented Apr 1, 2020 at 22:40

1 Answer 1

2

You may use it like this:

#!/usr/bin/env bash

condition=$(((RANDOM % 2) == 1))

if ((condition)); then
    echo "a"
else
    echo "b"
fi

Note that you may also shorten variable assignment to this:

condition=$((RANDOM % 2))
Sign up to request clarification or add additional context in comments.

4 Comments

fantastic, thanks. this happens when you are too lazy to read the manual and try to learn it from tutorials :D
y, I figured meanwhile I can shorten it, thanks. I was just not sure how automatic the type conversion is
There is no type conversion. You may do math, but the result is stored as a string; refer to it in an arithmetic context again, and it converts back from string to integer again each time. (There are exceptions to that; one can use declare -i to make a variable's native form arithmetic, but that's more a side note than anything)
@inf3rno Shell syntax and semantics are a lot more context-dependent than in most languages, so this may be throwing you. For example, depending on context a = b might mean "run the command 'a' with arguments '=' and 'b'; or it might mean "compare 'a' and 'b' as strings"; or it might mean "figure out what number b represents (probably by treating it as a variable name), and set the variable a to it". Another thing that throws people is that in shell syntax matters; adding or removing them can change the meaning of something completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.