Explanation: The excerpt C is a valid if condition in the Bourne shell because it uses the correct syntax and operators for the test command. The syntax of the if statement in the Bourne shell is:
if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fi
The test-commands are any commands that return a status of 0 (true) or non-zero (false). The test command is a common way to perform various tests on files, strings, and numbers. The test command has the following format:
test expression
The expression consists of one or more primaries, which are unary or binary operators that evaluate to true or false. The primaries can be combined with the following operators:
! expression: Logical NOT expression -a expression: Logical AND expression -o expression: Logical OR ( expression ): Parentheses for grouping
The excerpt C uses the test command with the following expression:
“$var” = “test”
This expression tests if the value of the variable $var is equal to the string “test”. The = operator is a string comparison operator that returns true if the strings are equal. The double quotes around the variable and the string are used to prevent word splitting and globbing by the shell. The spaces around the operator are also required by the test command.
The excerpt C also uses the correct syntax for the then and fi keywords, which mark the beginning and the end of the if statement. The then keyword must be on the same line as the test command, or on a new line after a semicolon. The fi keyword must be on a new line.
The other excerpts are invalid for various reasons:
- The excerpt A uses the && operator instead of the -a operator for logical AND. The && operator is a shell operator that executes the second command only if the first command succeeds. The test command does not recognize the && operator as a valid argument. The excerpt A also uses the != operator instead of the -ne operator for numeric comparison. The != operator is a string comparison operator that returns true if the strings are not equal. The -ne operator is a numeric comparison operator that returns true if the numbers are not equal.
- The excerpt B uses the [ [ construct instead of the test command. The [ [ construct is a shell keyword that performs conditional expressions similar to the test command, but with some extensions and differences. The [ [ construct is not part of the POSIX standard and is not supported by all shells. The Bourne shell does not support the [ [ construct, and will treat it as a command name. The excerpt B also uses the wrong syntax for the then keyword, which must be on a new line or after a semicolon.
- The excerpt D uses the wrong syntax for the test command, which requires a space after the opening bracket and before the closing bracket. The excerpt D also uses the wrong syntax for the fi keyword, which must be on a new line.