2

I am trying to make a bash script with the output based on the input. My code looks like this:

#!/bin/bash  
echo "Letter:"
read a
if a=3
then 
        echo "LOL"
fi
if a=4
then
        echo "ROFL"
fi

But when I enter 3 or 4, I get both LOL and ROFL. Is there a way for me to get LOL for 3 and ROFL for 4? Sorry if I'm using incorrect terms and stuff, I'm new to bash scripting.

3 Answers 3

3

In bash, a=3 is an assignment, not a test. Use, e.g.:

if [ "$a" = 3 ]

Inside [...], the equal sign tests for string (character) equality. If you want to test for numeric value instead, then use '-eq` as in:

if [ "$a" -eq 3 ]

The quotes around "$a" above are necessary to avoid an "operator" error when a is empty.

bash also offers a conditional expressions that begin with [[ and have a different format. Many like the [[ format better (it avoids, for example, the quote issue mentioned above) but the cost is loss of compatibility with other shells. In particular, note that dash, which is the default shell (/bin/sh) for scripts under Debian-derived distributions, does not have [[.

Sign up to request clarification or add additional context in comments.

Comments

2

Bash thinks you're trying to assign a variable by saying a=3. You can do the following to fix this:

  • Use the = operator whilst referencing the variable with a $, like so: if [[ $a = 3 ]]

  • Use the -eq operator, which is special and doesn't require you to reference the variable with a $, but may not be compatible with all sh-derived shells: if [[ a -eq 3 ]]. If you wish to use -eq without Bash reference the variable: if [[ $a -eq 3 ]]

Note:

The double square brackets [[ ... ]] are a preferred format with specifically Bash conditionals. [ ... ] is good with any sh-derived shell (zsh, tcsh, etc).

1 Comment

@MistressDavid it is possible but not 100% compatible with other shells. See this question.
2

if a=3 will assign value 3 to variable a unless a is readonly variable, if a=3 always returns TRUE same for if a=4

To compare variable a with a value, you can do this if [ $a = 3 ] so the script should change to

#!/bin/bash
echo "Letter:"
read a
if [ $a = 3 ]
then
        echo "LOL"
fi
if [ $a = 4 ]
then
        echo "ROFL"
fi

Since a is read from user input, there is possibility user key in:

  1. non numeric value
  2. a string with empty space
  3. nothing, user may just press Enter key

so a safer way to check is:

if [ "x$a" = "x3" ]

1 Comment

or you can just use [[ $a = 3 ]], no problems here.

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.