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.
You need Arithmetic Expansion: $((expression))
if [ $x = $(($# - 2)) ]; then
# ^ ^ ^ ^ ^ spaces are mandatory
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
ifcommand 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