The fundamental conditional instruction
if..then..elif..else..fi is slightly different from the traditional notation found in C. Its structure is:
if [condition1]; then
code1
elif [condtion2]; then
code2
else
code3
fi
The meaning of the different commands is this:
- if: executes code1 if the [condition1] is true.
- then: tells where the code to be executed according to the condition begins.
- elif: equivalent of else if in C. Executes code2 if [condition2] is true, but [condition1] is not true. It also terminates the part of code executed by the previous if / elif.
- else: executes code3 if none of the previous conditions is true.
- fi: ends the conditional block.
The following script checks if a file exists:
#!/bin/bash
if [ -f topolino.c ];
then
cat topolino.c
else
echo "The file does not exists"
fi
File checks
The conditions are always written inside square brackets. Note that the opening bracket should always be followed by a space, and the closing one preceded by a space. A series of operators exists in order to verify files conditions, according to the following syntax:
[ check_operator /etc/file_to_check]
These controls are:
Operator | Meaning |
-d: | Checks that the file is a directory |
-e: | Checks that the file exists |
-f: | Checks that the file is regular |
-g: | Checks that the SGID bit is set |
-r: | Checks that the file has the permissions for reading for the user executing the script |
-s: | Checks that the file has a non zero dimension |
-u: | Checks that the SUID bit is set |
-w: | Checks that the file is writable |