0

I'm begginer in linux console; I want to create if statement with integer variables

if[$x= [$#-2]]

But console receive if can't find this statment if[1 = [5-2]] Please help me and correct my statement.

1
  • Please learn at least this from your question: bash (and other shells) is very whitespace sensitive -- lines are split into tokens with whitespace. The if command needs a space between it and its conditional command. [ is a command in the shell, not just syntax. The = operator needs spaces around it. When in doubt, use spaces. Further documentation: gnu.org/software/bash/manual/bashref.html#Shell-Syntax Commented Nov 28, 2015 at 16:07

2 Answers 2

3

You need Arithmetic Expansion: $((expression))

if [ $x = $(($# - 2)) ]; then
# ^ ^  ^ ^           ^ spaces are mandatory
Sign up to request clarification or add additional context in comments.

1 Comment

@jan345 Karoly not only mentions the arith expansion but also the spaces. You need the spaces with all if-statements!
0

To start $# is the number of parameters passed to the bash script

./bash_script 1 2 3

$# auto-magically populates to 3. I hope you know this already.

#!/bin/bash
x=1
#If you are trying to compare `$x` with the value of the expression `$# - 2` below is how you do it :
if (( $x == $# - 2 ))
then
echo "Some Message"
fi
#If you are trying to check the assignment to `$x was successful below is how you do it :
if (( x = $# - 2 ))
then
echo "Some Message"
fi

The second condition is almost always true, but the first can be false. Below are the results of my test runs :

#Here the both ifs returned true
sjsam@WorkBox ~/test
$ ./testmath1 1 2 3 
Some Message
Some Message
#Here the first if returned false because we passed 4 parameters
sjsam@WorkBox ~/test 
$ ./testmath1 1 2 3 4
Some Message

1 Comment

@jan345 : Here the first part is for comparison. Did you try it?

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.