Control Structures in Scripts II
test
if [ -d "$MYNEWPATH" ]; then
echo "The " $MYNEWPATH " directory exists."
echo "Adding the " $MYNEWPATH " directory to PATH."
PATH=$PATH:$MYNEWPATH
export PATH
echo "Your PATH environment variable is now:"
echo $PATH
else
echo $MYNEWPATH " doesn’t exist."
fi
exit 0
In this example, the
[ –d “$MYNEWPATH” ]
condition calls a utility called test and directs it to check and see if the directory contained in the MYNEWPATH variable exists (as specified
by the –d option).
If test returns a value of TRUE, the steps immediately under the if statement are executed.
However, if the test program returns a value of FALSE, the statements under the else portion of the structure are executed. In this case, an error message will be displayed indicating that the
directory doesn’t exist.
In addition to using the –d option in the if/then/else structure to test a condition, you can also
use the test command itself. You can use the following options with test:
–d: Checks to see if the specified file exists and if it is a directory.
–e: Checks to see if the specified file exists. However, it does not differentiate between
files and directories.
–f: Checks to see if the specified file exists and if it is a regular file.
–G: Checks to see if the specified file exists and is owned by a specified group.
–h or –L: Checks to see if the specified file exists and if it is a symbolic link.
–O: Checks to see if the specified file exists and if it is owned by the specified user ID.
–r: Checks to see if the specified file exists and if the read permission is granted.
–w: Checks to see if the specified file exists and if the write permission is granted.
–x: aChecks to see if the specified file exists and if the execute permission is granted.
You can do more than test whether files exist with the test command. Some sample conditions you can evaluate with test are shown next.
True if the text is the same:
test "text1" = "text2"
True if strings are not equal:
test "text1" != "text2"
True if both numbers are the same:
test num1 -eq num2
True if num1 is less than num2:
test num1 -lt num2
True if num1 is greater than num2:
test num1 -gt num2
LX0-104 Exam Objectives (F)
No comments:
Post a Comment