User Commands IF (1)
Name if, Test - Evaluate Condition (s) Or Make Execution of Actions Dependent Upon The Evaluation of Condition (s)
Synopsis / usr / bin / test [condition]
Condition
SH10; THEN Action; Fi
IF Condition; Else Action2; Fi
IF Condition; Elif Condition2; Then Action2; ...;
IF Condition; Elif Condition2; Then Action2; ...; Else Action3; Fi
Test Condition
[Condition]
CSH IF (condition) THEN
Action
Else IF (condition2) THEN
Action2
Else
Action3
ENDIF
IF (condition) [action]
KSH IF CONDITION; THEN Action; Fi
IF Condition; Else Action2; Fi
IF Condition; Elif Condition2; Then Action2; ...;
IF Condition; Elif Condition2; Then Action2; ...; Else Action3; Fi
Test Condition
[Condition]
DESCRIPTION / usr / bin / test The test utility evaluates the condition and indicates the result of the evaluation by its exit status. An exit status of zero indicates that the condition evaluated as true and an exit status of 1 indicates that the condition evaluated as false .
In The Second Form of the Utility, Which Uses [] Rather THAN TEST, The Square Brackets Must Be Separate Arguments and condition is optional.
See Largefile (5) for the description of the behavior of test when encountering files Greater TEST I Equal to 2 gbyte (2 ** 31 bytes).
sh The condition following if is executed and, if it returns a 0 exit status, the action following the first then is executed. Otherwise, the condition2 following elif is executed and, if its value is 0, the action2 following the next then is executed. Failing the if and elif conditions, the else action3 is executed. If no else action or then action is executed, the if command returns a 0 exit status. Any number of elif ... then ... branching pairs are allowed , But Only One else.test Evaluates The Condition and, IF ITS Value Is True, Sets Exit Status To 0; OtherWise, A Non-Zero (False) EXIT Status Is Set; Test Also Sets A Non-Zero EXIT STATUS IF There Are no arguments. When Permissions Are Tested, The Effective User ID of The Process IS Used.
All Operators, Flags, And Brackets (Brackets Used As Shown In The Second Synopsis Line) Must Be Separate Arguments to the Test Command; Normally these Items area Separated by Spaces.
Primitives: The Following Primitives Are Used to Construct Condition:
-r filename true if filename exissrs and is readable.
-w filename true if filename exissrs and is write.
-x filename true if filename exissrs and is exduable.
-f filename True if filename exists and is a regular file. Alternatively, if / usr / bin / sh users specify / usr / ucb before / usr / bin in their PATH environ- ment variable, then test will return true if filename exists and IS (Not-a-Directory). This is also the default for / usr / bin / csh user.
-d filename True if filename exists and is a directory.-h filename True if filename exists and is a symbolic link. With all other primitives (except -L filename), the symbolic links are followed by default.
-c filename true if filename exissrs and is a character SPE- Cial File.
-b filename true if filename exissrs and is a blue special file.
-P filename true if filename exissrs and is a named pipe (FIFO).
-u FileName True if FileName EXISTS AND ITS SET-USER- ID BIT IS SET.
-g FileName True if FileName EXSTS AND ITS SET-Group- ID Bit is Set.
-k filename true if filename exists and its sticky bit is set.
-s filename true if filename exists and has a size greater tour Zero.
-T [Fildes] True IF The Open File Whose File Descriptor Number is Fildes (1 by default) IS Associated with a Terminal Device.
-z S1 Trueness The Length of String S1 is Zero.
--N S1 True IF The Length of The STRING S1 IS NON-ZERO.
S1 = S2 True IF STRINGS S1 AND S2 Are Identical.
S1! = S2 True IF STRINGS S1 and S2 Are Not Identical.
S1 TRUE IF S1 IS NOT The NULL STRING.
N1 - EQ N2 True IF The Integers N1 and N2 Are Algebraically Equal.
N1 - N2 TRUE IF The INTEGEBRAI- CALLY Equal.
N1 -GT N2 True IF The INTEGER N1 IS Algebraically Greater THEN THE INTEGER N2.N1 - THEGEBRAICLY GREATER THAN OR Equal to the integer N2.
N1 -LT N2 TRUE IF The INTEGER N1 IS Algebraically Less Than The Integer N2.
N1 --LE N2 TRUE IF The INTEGER N1 IS Algebraically Less Than or Equal To The Integer N2.
-L FileName True if FileName EXISTS AND is a symbolic link. With all other primitives (Except -h filename), The Symbolic Links Are Followed by Default.
Operators: these priMaries May Be Combined with The Following Opera- Tors:
! Unary Negation Operator.
-A binary and operator.
-o binary or operator (-A Has Higher Precedency Than -O).
.....................
The NOT-A-Directory Alternative to the -f Option IS A TRAN- SITION AID for BSD Applications and May Not Be Supported in Future Releases.
The -l Option IS A MIGRATION AID for Users of Other Shells Which Have Similar Options and May Not Be Supported in Future Releases.
If you test a file you ing (the -r -w or -x tests), But The Permission Tested Does Not Have The Owner Bit Set, A Non- Zero (false) Exit Status Will Be Returned Even Thountain THE File May Have the Group Or Other Bit Set for That Permis- Sion. The Correct Exit Status Will Be set if you are super- user.
The = and = operators have a higher precedence than the -r through -n operators, and = and = always expect arguments;!! Therefore, = and = can not be used with the -r through -n operators.If more than one! Argument Follows The -r Through -n Opera- Tors, Only The First Argument is Examined; The Others Are Ignored, Unless A -A OR A -O is The Second Argument.
csh With the multi-line form of if: if condition is true, the action up to the first else or then is executed Otherwise, if else if condition2 is true, the action2 between the else if and the following else or then is executed. OtherWise, The Action3 Between The else and the endif is executed.
The if must appear alone on its input line or after an else. Only one endif is needed, but it is required. The words else and endif must be the first nonwhite characters on a line. Any number of else if ... then. .. Branching Pairs are allowed, but only one else.
endif keywords: With the one- line form of if, there are no else, then, or if the specified condition evaluates to true, the single action with arguments is executed Vari- able substitution on action happens early, at the same time it. does for the rest of the if command. action must be a simple command, not a pipeline, a command list, or a parenthesized command list. Note that I / O redirection occurs even if condi- tion is false, when action is not executed (this is a bug) .ksh The condition following if is executed and, if it returns an exit status of 0, the action following the first then is executed. Otherwise, the condition2 following elif is executed and, if its value is 0, The Action2 Following The next kiln ing That, The else action3 is exe- creted. If no else Action or death is Executed, THE IF COMMAND RETURns An EXIT STATUS OF 0. Any Number of Elif ... Then ... Branching Pairs are allowed, but Only One else.
For A Description of the Test Built-in, See The Ksh (1) Sec - TIONS CONDITIONAL EXPRESSION AND ARITIC EVALE SHELL AS TEST Built-in Above.
[Condition] Evaluates File Attributes, String Comparisons, and Compound "AND" or "contditions.
Operands All Operators and Elements of Primaries Must Be Presented As Separate Arguments to the Test Utility.
The Following Primaries Can Be Used to Construct Condition:
-a file true, if file exisss.
-b file true if file exissrs and is a block special file.-c file true if file exissrs and is a character special file.
-d file true if file exissrs and is a directory.
- E File True if File EXISTS.
-f File True if file exissrs and is a regular file.
-g File True If File EXSTS AND ITS SET GROUP ID FLAG IS SET.
-k file true, if File Excents and is has it it its sticky bit set.
- N String True if the length of string is non-zero.
-o Option true, if Option named option is on.
-p file true if file is a named pipe (FIFO).
-r file true if file exissrs and is readable.
-s File True if File Exists and has a size greater tour ze.
-t file_descriptor true if the file whose file descriptor Number is file_descriptor is open and is associated with a Terminal.
-u file true if file exissrs and its set-user-id flag is set.
-w file true if file exissrs and is write. True Will Indicate Only That The Write Flag Is On. The File Will NOT BE WRITABLE ON A Read-Only File System Even IF This Test Indicates True.
-x file true if file exissrs and is executable. True Will Indicate Only That The Execute Flag Is On. If File IS A Directory, True INDICES THAT FILE CAN Be Searched.
-z string Trueness is Zero.
-L file true, if file exissrs and is a symbolic link.-o File true, if file exissrs and is outprue Group ID of this process.
-S file true, if file exissrs and is a socket.
File1-NT File2 True, if File1 EXSTS AND IS NEWER THAN FILE2.
File1-Ot File2 True, if File1 EXSTS AND IS OLDER THAN FILE2.
File1-Ef file2 true, if file1 and file2 exist and refer to the same file.
String True if the string string is not the null string.
String = pattern true, if string matches pattern.
String! = Pattern True, if String Does Not Match Pattern.
String1 = string2 true if the strings string1 and string2 Are Identical.
String1! = String2 True if The strings string1 and string2 Are not identical.
String1 String1> string2 true, if string1 comes after string2 based on ascii value of their character character N1 - EQ N2 True IF The Integers N1 and N2 Are Algebraically Equal. N1-N2 "True IF the INTEGEBRAI- CALLY EQUAL. N1 -GT N2 "True IF The INTEGER N1 IS Algebraically Greater Than the Integer N2. N1 -GE N2 "True If the INTEGER N1 IS Algebraically Greater Than Or Equal to the Integer N2.N1 -LT N2" True IF The Integer N1 IS Algebraical LESS THEN THE INTEGER N2. N1 N2 "TRUE IF The INTEGER N1 IS Algebraically Less Than OR Equal to the Integer N2. Thase Primaries Can Be Combined with The Following Operator: ! Condition True if condition is false. The Primaries with Two Elements of the form: -Primary_operator primary_Operand Are Known as unary primaries. The primaries with three ele- ments in Either of the Two Forms: PRIMARY_OPERAND -PRIMARY_OPERATOR PRIMARY_OPERAND PRIMARY_OPERAND PRIMARY_OPERATOR PRIMARY_OPERAND Are Known as binary primaries. The algorithm for determining the precedence of the opera- tors and the return value that will be generated is based on the number of arguments presented to test. (However, when using the [...] form, the right-bracket final argument will Not be counted in this algorithm.) In The Following List, $ 1, $ 2,1 $ 3 and $ 4 represent the argu- momts presented to test. 0 Arguments: exit false (1). 1 argument: exit true (0) IF $ 1 is not null; OtherWise, Exit False. 2 arguments: o IF $ 1 is!, exit true if $ 2 is Null, False IF $ 2 is not null. o If $ 1 is a unary primary, exit true if the unary test is true, false. O OtherWise, Produce Unspecified Results. 3 arguments: o IF $ 2 IS A Binary Primary, Perform The Binary Test of $ 1 and $ 3. o IF $ 1 is!, Negate The Two-Argument Test of $ 2 and $ 3.o OtherWise, Produce Unspecified Results. 4 arguments: o IF $ 1 IS!, Negate The Three-Argument Test of $ 2, $ 3, And $ 4. o OtherWise, The Results is unspecified. USAGE Scripts should be careful when dealing with user-supplied input that could be confused with primaries and operators Unless the application writer knows all the cases that pro- duce input to the script, invocations like.: TEST "$ 1" -a "$ 2" Should Be Written As: Test "$ 1" && test "$ 2" To Avoid Problems if A User Supplied Values Such AS $ 1 set to! and $ 2 set to the null string. That is, in case where maximal portability is of concern, replace: TEST EXPR1 -A EXPR2 With: Test Expr1 && Test Expr2 And Replace: TEST EXPR1 -O EXPR2 With: Test expr1 || test expr2 But Note That, in Test, -a Has Higher Precedency Than -O While && and || Have Equal Precedency In The Shell. Parentheses or braces can be used in the shell command language to effect grouping. Parentheses Must Be Escaped When Using Sh; for Example: TEST / (Exp1 -a EXPR2 /) -O EXPR3 This Command is Not ALWAYS Portable Outside XSI-Conformant Systems. The Following Form Can Be Used Instead: (TEST EXPR1 && Test EXPR2) || Test EXPR3 The Two Commands: Test "$ 1" TEST! "$ 1" Could Not Be Used Reliably on Some Historical Systems. Unex- PECTED RESULDS WERE Used and $ 1 Expanded To! (OR A KNOWN UNARY PRIMARY). Better Construction Are: Test -n "$ 1" TEST -Z "$ 1" Respectively. Historical Systems Have Also Been Unreliable Given The COM- MON Construct: Test "$ response" = "expected string" One of the following is a more reliable form: Test "x $ response" = "Xexpected String" TEST "Expected String" = "$ cyponse" Note that the second form assumes that expected string could not be confused with any unary primary If expected string starts with -.!., (, Or even =, the first form should be used instead Using the preceding rules without the marked exten- sions Any of the Three Comparison Forms IS Reliable, Given Any INPUT. (HOWEVER, NOTE That the strings.) Because the string comparison binary primaries, = and! =, Have a higher precedence than any unary primary in the> 4 argument case, unexpected results can occur if arguments are not properly prepared. For example, in TEST -D $ 1 -o -D $ 2 If $ 1 evaluates to a possible directory name of =, the first three arguments are considered a string comparison, which causes a syntax error when the second -d is encountered is encountered One of the following forms prevents this; the second is preferred..: TEST / (-D "$ 1" /) -o / (-d "$ 2" /) TEST -D "$ 1" || TEST -D "$ 2" Also in the> 4 Argument Case, TEST "$ 1" = "bat" -a "$ 2" = "ball" SYNTAX Errors Will Occur IF $ 1 Evaluates To (OR!. One of the Following Forms Prevents this; The third is preferred: TEST "x $ 1" = "xbat" -a "x $ 2" = "xball" test "$ 1" = "BA" && test "$ 2" = "Ball" test "x $ 1" = "xbat" && test "x $ 2 "=" Xball "Examples in The IF Command Examples, Three Conditions Are Tested, Andiff All Three Evaluate As True Or Successful, THEIR Validities Are Written To The Screen. The 3 Tests Are: Oiff a variable set to 1 is greater tour 0, Oiff a variable set to 2 is equal to 2, and o iF the word "root" is incruded in the text file / etc / passwd. / usr / bin / test esample 1: using / usr / bin / test Perform a Mkdir if A Directory Does Not Exist: Test! -d Tempdir && Mkdir Tempdir Wait for a file to become non-readable: While Test -r thefile do sleep 30 done echo '"Thefile" is no longer readable " Perform A Command if The Argument is One of Three Strings (Two Variations): IF ["$ 1" = "pear"] | | ["$ 1" = "apple"] Then Command Fi Case "$ 1" in pear | grape | apple) Command ;; ESAC . Example 2: using the shfort-in ZERO = 0 One = 1 TWO = 2 root = root IF [$ one -gt $ zero] [$ Two -eq 2] GREP $ root / etc / passwd> & 1> / dev / null # discard output THEN Echo "$ ONE IS GREATER THAN 0, $ Two Equals 2, And $ ROOT IS A User-name in the password file" Else Echo "At Least One of the Three Test Conditions IS False" FI Example 3: using the test built-in Examples of the test built-in: Test `Grep $ root / etc / passwd> & 1 / dev / null` # discard Output Echo $? # Test for success [`grep nosuchname / etc / passwd> & 1 / dev / null`] Echo $? # Test for Failure CSH Example 4: Using the csh Built-in @ Iono = 0; @ One = 1; @ two = 2; set root = root grep $ root / etc / passwd> & 1 / dev / null # discard output # $ status must be tsted for Immedierately Following Grep if ("$ status "==" 0 "&& $ ONE> $ zero && $ two == 2) THEN Echo" $ ONE IS GREATER THAN 0, $ Two Equals 2, and $ root is a user-name in the password file "Endif KSH EXAMPLE 5: USING THE KSH Built-in ZERO = 0 One = 1 Two = $ (One One)) Root = root if ((One> Zero)) # Arithmetical Comparison [[$ TWO = 2]] # String Comparist [`Grep $ root / etc / passwd > & 1 / dev / null`] # discard output the echo "$ ONE IS GREATER THAN 0, $ Two Equals 2, and $ root is a user-name in the password file Else Echo "At Least One of the Three Test Conditions IS False" FI ............ .. ....................... .. ENVIRONMENT VARIABLES See environ (5) for descriptions of the following environment variables that affect the execution of test: LC_CTYPE, LC_MESSAGES, and NLSPATH.EXIT STATUS The following exit values are returned: 0 Condition Evaluated to True. 1 Condition Evaluated to false or condition WAS MISSING. > 1 An error accurred. Attributes See Attributes (5) for descriptions of the folload attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | | _____________________________ | _____________________________ | | Availability | SUNWcsu | | _____________________________ | _____________________________ | See Also CSH (1), KSH (1), SH (1), Test (1B), Attributes (5), Environ (5), Largefile (5) NOTES BTH The Bourne Shell, Sh, And The Korn Shell, Ksh