Score:0

Bash from scratch

cn flag

I know this may sound ridiculous, but in my defence I'll say I'm at the very beginning of messing around with coding and bash in particular, so don't judge me too harshly...

I just dipped into this:

#!/bin/bash

echo -n "Enter a number: "
read VAR

if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
fi

Thing is any number I write up doesn't change a thing. Even 2 will be greater than 10. What's wrong?

Karlom avatar
de flag
This scrpt works fine for me: `Enter a number: 12 The variable is greater than 10.` What's exactly the problem ?
paladin avatar
kr flag
Please do `ls /bin/bash -l` and tell us what the output is. `/bin/bash --version` would also help.
terdon avatar
cn flag
You have two bad practices there: i) avoid using CAPS for variables. By convention, global environment variables are in CAPS and if you set yours that way too that can cause surprising bugs. ii) Always quote your variables when using them.
Score:5
vn flag

The script has a correct syntax, and works for me. If I enter anything from 0-10, it does not echo any text.

For future reference, I recommend you install shellcheck and make a habit of checking your script syntax with it.

Score:2
us flag

Alternatively (since you mention that you are learning bash) you could use an arithmetic expression:

if (( VAR > 10 ))
then
    echo "The value is greater than 10."
fi

Or the more concise one-liner:

(( VAR <= 10 )) || echo "The value is greater than 10."
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.