File Conditional Expressions in Bash
What are conditional expressions?
When we use conditional statements like if we need to pass some conditions to check whether it's true or not and based on that information we execute some commands.
For example:
=4
The above program checks that if the value of i is greater than 2 or not if true it prints "i is greater than 2".
The i>2 is conditional expression.
Likewise bash also have conditional expressions but the syntax is unique. Conditional expressions in bash are targeted more towards the Linux usability like checking conditions on files, directories etc.
Conditional Expressions for Files
Here is a example code:
#! /usr/bin/env bash
filename=./array5.sh
if ; then
else
fi
if ; then
else
fi
if ; then
fi
if ; then
fi
if ; then
fi
if ; then
fi
if ; then
else
fi
In the above code we have multiple if then statements that the checking some conditions on file array5.sh whole name is stored at the top in the variable name filename.
Let's see the first if then statement block:
filename=./array5.sh
if ; then
else
fi
- Here I have condition
[[ -a ${filename} ]]for if statement. - This will check whether the file exists or not in the current directory(because the file path is
./array5.sh,.means the current directory) . - If the file exists then the program will execute the
thenblock and messageThe file exists!will be printed. - If the file
array5.shdoesn't exists in the current directory then the program will executeelseblock and messageThis file doesn't exists!will print in the console. - The ending
fiis the syntax of the bashifstatement, it is there to indicate the closing of theifblock.
There are other conditional expressions for files:
[[ -d ${filename} ]]: True if the file is a directory.[[ -r ${filename} ]]: True if file exists and readable.[[ -s ${filename} ]]: True if file exists and has size larger than zero.(To check empty files)[[ -w ${filename} ]]: True if file exists and writable.[[ -x ${filename} ]]: True if file exists and executable.[[ -L ${filename} ]]: True if file is a symbolic link.
Note: The -x ,-w, -r flags check the file permissions for the user that is running the script.