📅  最后修改于: 2023-12-03 14:59:23.645000             🧑  作者: Mango
if
statements are used in shell/bash scripting to control the flow of execution of the script based on certain conditions being met.
The basic structure of an if
statement in shell/bash is:
if [ condition ]
then
# code to be executed if condition is true
else
# code to be executed if condition is false
fi
In this structure, the condition
is an expression that is evaluated to either true or false. If the condition is true, the code inside the then
block is executed, and if the condition is false, the code inside the else
block (if present) is executed.
Here is an example showing the use of an if
statement to check if a file exists:
if [ -f /path/to/file ]
then
echo "File exists"
else
echo "File does not exist"
fi
In this example, the -f
option is used to check if the given file exists. If it does exist, the message "File exists" is printed; if it doesn't exist, the message "File does not exist" is printed.
Other common conditions used in if
statements in shell/bash include:
-d
- check if a directory exists-n
- check if a string is not empty-z
- check if a string is empty-eq
- check if two numbers are equalHere's an example showing the use of if
statements with some of these conditions:
if [ -d /path/to/directory ]
then
echo "Directory exists"
else
echo "Directory does not exist"
fi
if [ -n "$VAR" ]
then
echo "String is not empty"
else
echo "String is empty"
fi
if [ "$NUM1" -eq "$NUM2" ]
then
echo "Numbers are equal"
else
echo "Numbers are not equal"
fi
These examples should give you an idea of how to use if
statements in shell/bash scripting to control the flow of execution based on various conditions.