Conditional execution
Conditional execution means that you can choose to execute code only if certain conditions are met. Without this capability, all you would be able to do is execute one command after another after another. The ability to test a variety of things about the state of the system, and of the environment variables of the process, means that a shell script can do far more powerful things that would otherwise be possible.
Syntax:
[ condition-to-test-for ]
Example:
[ -e /etc/passwd ]
This tests if etc/passwd exists, and if it does this returns true - command exit status of 0
. If it doesn't exist the command exits with the exit status of 1
. The spaces around the [
and ]
symbols are required!
File test operators:
-d FILE #True if the file is a directory
-e FILE #True if the file exists
-f FILE #True if the file exists and it's regular file
-r FILE #True if the file is readable by you
-s FILE #True if the file exists and it's not empty
-w FILE #True if the file is writable by you
-x FILE #True if the file is executable by you
String test operators:
-z STRING #True if the string is empty
-n STRING #True if the string is not empty
STRING1 = STRING2 #True if the strings are equal
STRING1 != STRING2 #True if the strings are not equal
Arithmetic tests:
arg1 -eq arg2 #True if the arguments are equal
arg1 -ne arg2 #True if the arguments are not equal
arg1 -lt arg2 #True if the arg1 is less than arg2
arg1 -le arg2 #True if arg1 is less than or equal to arg2
arg1 -gt arg2 #True if arg1 is greater than arg2
arg1 -ge arg2 #True if arg1 is greater than or equal to arg2
Examples
Example 1. Check what shell.
-
Input
Example 2. Check if a file is readable
-
Input
Example 3. Identify OS.
-
Input
Example 4. Check a word.
-
Input