Use the preceding example to write a conditional expression. If the first parameter does not exist, no parameter is output; otherwise, the first parameter is output.
#!/bin/bashif [ -n "$1" ]then echo "1st parameter: $1"else echo "no parameter"fi
Enter the command with parameters:
$ ./test.sh 'this is a test'1st parameter: this is a test
Enter the command without parameters:
$ ./test.shno parameter
Explain the Condition Statement first:
If [...]
Then
...
Else
...
Fi
... Indicates where statements can be written.
You must end the entire Condition Statement with Fi.
Note that [...] square brackets must be separated by spaces.
-N is an operator that determines whether the subsequent parameter length is 0. If it is not 0, true is returned. If it is 0, false is returned.
This document is a good introduction. For details, refer:
Http://v.youku.com/v_show/id_XNDQ5ODE3MDQw.html
The complex conditional expressions are as follows:
if condition1thenstatement1statement2..........elif condition2thenstatement3statement4........ elif condition3thenstatement5statement6........ fi
In addition to-N, there are other operators available for use:
Operator |
Produces true if... |
Number of operands |
-N |
Operand non zero length |
1 |
-Z |
Operand has zero length |
1 |
-D |
There exists a directory whose name isOperand |
1 |
-F |
There exists a file whose name isOperand |
1 |
-EQ |
The operands are integers and they are equal |
2 |
-NEQ |
The opposite of-EQ |
2 |
= |
The operands are equal (as strings) |
2 |
! = |
Opposite of = |
2 |
-Lt |
Operand1Is strictly lessOperand2(Both operands shoshould be integers) |
2 |
-GT |
Operand1Is strictly greaterOperand2(Both operands shoshould be integers) |
2 |
-Ge |
Operand1Is greater than or equalOperand2(Both operands shoshould be integers) |
2 |
-Le |
Operand1Is less than or equalOperand2(Both operands shoshould be integers) |
2 |
The double operand operator is used as follows:
$r -eq 1