Sponsored Content
Top Forums UNIX for Dummies Questions & Answers brackets vs parentheses - single and double Post 302240411 by jim mcnamara on Thursday 25th of September 2008 05:28:56 PM
Old 09-25-2008
First read the man page for test.

[[ and [ are shell builtins (in modern shells)
for test. test or [[ - you have to complete them with ]] - are use either in if statments or in combined statements
Code:
if [[ 1 -eq $var ]] ; then
   echo "hi there"
fi
# same thing written another way as a one-liner
[[ 1 -eq $var ]] &&  echo "hi there"

# test if a file exists
[[ -f somefile ]] && echo "found somefile "

the -eq -gt -lt -ge -le comparisons are for comaring integer numbers in [[ ]]
comparing strings- [[ "$string1" = "$string2" ]]

There are other modern operators for testing file times: for example -ot -nt
See the ksh man page

$(( )) does arithmetic operations - whole numbers (long integers).
allowed operators are + - * / and some others like %.
$(( 3 + 1 )) evaluates a 4

$( some command[s] ) runs one or more commands in background
it works just like the backticks: `command`
read all of a file into an envrionment variable
myvar=$(< somefile)
put the date in a variable
myvar=$( date )
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

single or double quote in SED

i m trying the following command but its not working: sed 's/find/\'replace\'/g' myFile but the sed enters into new line # sed 's/find/re\'place/g' myFile > I havn't any idea how to put single quote in my replace string. Your early help woud be appreciated. Thanx (2 Replies)
Discussion started by: asami
2 Replies

2. UNIX for Dummies Questions & Answers

why put double square brackets in an if clause?

what is the rationale behind putting double square brackets in an if clause? for e.g. if ] || ] || ]; then echo some fields are null fi (5 Replies)
Discussion started by: napolayan
5 Replies

3. Shell Programming and Scripting

WHy the double square brackets?

One of the senior administrators gave me a shell script to modify and it begins as follows: if ] && ] {more code follows} Why the double square brackets? (10 Replies)
Discussion started by: mojoman
10 Replies

4. Shell Programming and Scripting

Use of double square brackets in ksh

Hi First apologies if this has been raised before. I've got the following in a ksh script: if ] For some reason this does not work. But if I remove the double square brackets to: if This works. I thought ksh supported the ]. Or is there more to it? Thanks in advance. (3 Replies)
Discussion started by: tsu3000
3 Replies

5. Shell Programming and Scripting

why double brackets for array loop?

Dear All, Recently got some sample from internet search for array handle in shell script, and I can not understand why we need to put double brackets when extracting array values by this way : for ((i=0; i<${#admins}; i++)); do echo "${admins}" done if modify from double to single... (2 Replies)
Discussion started by: tiger2000
2 Replies

6. Shell Programming and Scripting

Double square brackets question

Hi, I just came across an interesting shell script syntax like the one below: ] && (trap 'rm -rf ${WORK_DIR}/*.$$; echo "\n\nInterrupted !!\n\n"; exit 4' 1 2 3 15) Can someone please explain the code snippet above? The trap command bit is fine but ] && is the hazy part. Generally we use an... (2 Replies)
Discussion started by: King Nothing
2 Replies

7. UNIX for Dummies Questions & Answers

Brackets, parentheses in Shell Scripting

Hello, I have done a great deal of research on this and still cannot come to an understanding of the following: In if-else statements in shell scripting I have seen examples of single brackets, double brackets, single parantheses, and double paratheses. When should each one be used? And... (2 Replies)
Discussion started by: mojoman
2 Replies

8. Shell Programming and Scripting

Rules with using double parentheses in Bash

Hi.could you explain me what are the rules when we are using double parentesis in if statement,if I put ,the code is working ,with (( is not #!/bin/bash if (($# > 0)) then if ((! -d "$1")) then echo "Directory $1 not found" fi else echo Problem fi (8 Replies)
Discussion started by: lio123
8 Replies

9. UNIX for Dummies Questions & Answers

Single or double square brackets

Hi frieds, I don't understand the difference between single square bracket and double square brackets in a IF condition. Ex. if ; then RETURNJOB=1 else RETURNJOB=0 fi It run, but this if ]; then RETURNJOB=1 else RETURNJOB=0 fi (4 Replies)
Discussion started by: dogshort
4 Replies

10. Shell Programming and Scripting

Replace double quotes with a single quote within a double quoted string

Hi Froum. I have tried in vain to find a solution for this problem - I'm trying to replace any double quotes within a quoted string with a single quote, leaving everything else as is. I have the following data: Before: ... (32 Replies)
Discussion started by: pchang
32 Replies
test(1) 							   User Commands							   test(1)

NAME
test - evaluate condition(s) SYNOPSIS
/usr/bin/test [condition] [ [condition] ] sh test [condition] [ [condition] ] csh test [condition] [ [condition] ] ksh test [condition] [ [condition] ] ksh93 test [condition] [ [condition] ] DESCRIPTION
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 first form of the utility shown using the SYNOPSIS: test [condition] the square brackets denote that condition is an optional operand and are not to be entered on the command line. In the second form of the utility shown using the SYNOPSIS: [ [ condition ] ] the first open square bracket, [, is the required utility name. condition is optional, as denoted by the inner pair of square brackets. The final close square bracket, ], is a required operand. See largefile(5) for the description of the behavior of test when encountering files greater than or equal to 2 Gbyte (2^31 bytes). The test and [ utilities evaluate the condition condition and, if its value is true, set exit status to 0. Otherwise, a non-zero (false) exit status is set. test and [ also set 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 last SYNOPSIS line) must be separate arguments to these commands. Nor- mally these arguments are separated by spaces. OPERANDS
The primaries listed below with two elements of the form: -primary_operator primary_operand are known as unary primaries. The primaries with three elements in either of the two forms: primary_operand -primary_operator primary_operand primary_operand primary_operator primary_operand are known as binary primaries. If any file operands except for -h and -L primaries refer to symbolic links, the symbolic link is expanded and the test is performed on the resulting file. If you test a file you own (the -r -w or -x tests), but the permission tested does not have the owner bit set, a non-zero (false) exit sta- tus is returned even though the file can have the group or other bit set for that permission. The = and != primaries have a higher precedence than the unary primaries. The = and != primaries always expect arguments; therefore, = and != cannot be used as an argument to the unary primaries. The following primaries can be used to construct condition: -a file True if file exists. (Not available in sh.) -b file True if file exists and is a block special file. -c file True if file exists and is a character special file. -d file True if file exists and is a directory. -e file True if file exists. (Not available in sh.) -f file True if file exists and is a regular file. Alternatively, if /usr/bin/sh users specify /usr/ucb before /usr/bin in their PATH environment variable, then test returns true if file exists and is (not-a-directory). The csh test and [ built-ins always use this alternative behavior. -g file True if file exists and its set group ID flag is set. -G file True if file exists and its group matches the effective group ID of this process. (Not available in sh.) -h file True if file exists and is a symbolic link. -k file True if file exists and has its sticky bit set. -L file True if file exists and is a symbolic link. -n string True if the length of string is non-zero. -o option True if option named option is on. This option is not available in csh or sh. -O file True if file exists and is owned by the effective user ID of this process. This option is not available in sh. -p file True if file is a named pipe (FIFO). -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -S file True if file exists and is a socket. This option is not available in sh. -t [file_descriptor] True if the file whose file descriptor number is file_descriptor is open and is associated with a terminal. If file_descriptor is not specified, 1 is used as a default value. -u file True if file exists and its set-user-ID flag is set. -w file True if file exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true. -x file True if file exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched. -z string True if the length of string string is zero. file1 -nt file2 True if file1 exists and is newer than file2. This option is not available in sh. file1 -ot file2 True if file1 exists and is older than file2. This option is not available in sh. file1 -ef file2 True if file1 and file2 exist and refer to the same file. This option is not available in sh. string True if the string string is not the null string. string1 = string2 True if the strings string1 and string2 are identical. string1 != string2 True if the strings string1 and string2 are not identical. n1 -eq n2 True if the integers n1 and n2 are algebraically equal. ksh93 also supports floating point numbers. n1 -ne n2 True if the integers n1 and n2 are not algebraically equal. ksh93 also supports floating point numbers n1 -gt n2 True if the integer n1 is algebraically greater than the integer n2. ksh93 also supports floating point numbers n1 -ge n2 True if the integer n1 is algebraically greater than or equal to the integer n2. ksh93 also supports floating point numbers n1 -lt n2 True if the integer n1 is algebraically less than the integer n2. ksh93 also supports floating point numbers n1 -le n2 True if the integer n1 is algebraically less than or equal to the integer n2. ksh93 also supports floating point numbers condition1 -a condition2 True if both condition1 and condition2 are true. The -a binary primary is left associative and has higher precedence than the -o binary primary. condition1 -o condition2 True if either condition1 or condition2 is true. The -o binary primary is left associative. These primaries can be combined with the following operators: ! condition True if condition is false. ( condition ) True if condition is true. The parentheses ( ) can be used to alter the normal precedence and associativity. The parenthe- ses are meaningful to the shell and, therefore, must be quoted. The algorithm for determining the precedence of the operators and the return value that is generated is based on the number of arguments presented to test. (However, when using the [...] form, the right-bracket final argument is not counted in this algorithm.) In the following list, $1, $2, $3 and $4 represent the arguments presented to test as a condition, condition1, or condition2. 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 if the unary test is 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 are 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 produce 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 cases 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 notice that, in test, -a has higher precedence than -o, while && and || have equal precedence 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 ( expr1 -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. Unexpected results would occur if such a string condition were used and $1 expanded to !, (, or a known unary primary. Better constructs are, respectively, test -n "$1" test -z "$1" Historical systems have also been unreliable given the common construct: test "$response" = "expected string" One of the following is a more reliable form: test "X$response" = "Xexpected string" test "expected string" = "$response" 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 extensions, any of the three comparison forms is reliable, given any input. (However, observe that the strings are quoted in all cases.) Because the string comparison binary primaries, = and !=, have a higher precedence than any unary primary in the >4 argument case, unex- pected 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 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" = "bat" && test "$2" = "ball" test "X$1" = "Xbat" && test "X$2" = "Xball" EXAMPLES
In the if command examples, three conditions are tested, and if all three evaluate as true or successful, then their validities are written to the screen. The three tests are: o if a variable set to 1 is greater than 0, o if a variable set to 2 is equal to 2, and o if the word root is included in the text file /etc/passwd. /usr/bin/test Example 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), using the open bracket version [ of the test command: if [ "$1" = "pear" ] || [ "$1" = "grape" ] || [ "$1" = "apple" ] then command fi case "$1" in pear|grape|apple) command;; esac Example 2 Using /usr/bin/test for the -e option If one really wants to use the -e option in sh, use /usr/bin/test, as in the following: if [ ! -h $PKG_INSTALL_ROOT$rLink ] && /usr/bin/test -e $PKG_INSTALL_ROOT/usr/bin/$rFile ; then ln -s $rFile $PKG_INSTALL_ROOT$rLink fi The test built-in The two forms of the test built-in follow the Bourne shell's if example. Example 3 Using the sh built-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 4 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 5 Using the csh built-in @ ZERO = 0; @ ONE = 1; @ TWO = 2; set ROOT = root grep $ROOT /etc/passwd >&1 /dev/null # discard output # $status must be tested for immediately 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 6 Using the ksh built-in ZERO=0 ONE=1 TWO=$((ONE+ONE)) ROOT=root if ((ONE > ZERO)) # arithmetical comparison [[ $TWO = 2 ]] # string comparison [ `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 ENVIRONMENT VARIABLES
See environ(5) for descriptions of the following environment variables that affect the execution of test: LANG, LC_ALL, LC_CTYPE, LC_MES- SAGES, 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 occurred. ATTRIBUTES
See attributes(5) for descriptions of the following attributes: /usr/bin/test, csh, ksh, sh +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Availability |SUNWcsu | +-----------------------------+-----------------------------+ |Interface Stability |Committed | +-----------------------------+-----------------------------+ |Standard |See standards(5). | +-----------------------------+-----------------------------+ ksh93 +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Availability |SUNWcsu | +-----------------------------+-----------------------------+ |Interface Stability |Uncommitted | +-----------------------------+-----------------------------+ SEE ALSO
csh(1), ksh(1), ksh93(1), sh(1), test(1B), attributes(5), environ(5), largefile(5), standards(5) NOTES
The not-a-directory alternative to the -f option is a transition aid for BSD applications and may not be supported in future releases. When comparing file timestamps, the ksh93 test built-in handles high-resolution timestamps of up to nanosecond granularity, for file sys- tems which support them. SunOS 5.11 20 Nov 2007 test(1)
All times are GMT -4. The time now is 06:10 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy