I have seen scripts using the test command and [ ] or [[ ]]. But when do we need to use /usr/bin/test and (( ))?
Are there any occasions when we need to go for the latter?
Regards,
John
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To answer your question:
/usr/bin/testwhen you want totestsomething but not in a shell (for examplefind ... -exec test ...)(( ))when you have an arithmetic expression to solve, AND you are using bash, because(( ))is bash specific.Now for some background:
The command
/usr/bin/testis required by the POSIX standard. POSIX also requires that[is defined as an alias fortest. The only difference betweentestand[is that[requires the final parameter to be a].Since
testis used so frequently in shell scripts, most shells have a builtin version oftest(and[). The advantage of a builtin is that it avoids context switches. Which, depending how you usetestin your script, can be a measurable performance advantage.I think it is safe to assume that under most circumstances it doesn’t matter whether you use the system
testor the shell’s builtintest. But if you want to usetestin afind -execsituation then of course you have to use the systemtestbecausefindcannot use the shelltest.(( ))and[[ ]]were introduced by bash (and perhaps some other shells) as syntactic sugar.(( ))evaluates arithmetic expressions, while[[ ]]evaluates logical expressions. Both allow you to write the expressions in a "more natural syntax".The decision to use
[[or[depends on whether you want to use the "more natural syntax", and, since sh does not support[[, whether you want to depend on bash.The decision to use
(( ))depends on whether you need arithmetic expressions, and again, since sh does not support(( )), whether you want to depend on bash. The POSIX alternative to(( ))is$(( )). Note that there are some subtle differences in the behaviour.The following links explain these topics in great detail:
test,[and[[)let,(( ))and$(( )))See also:
test$(( ))Bonus: Some debian developers once argued whether they should use the system
testor the shell builtintest, because of some differences in the implementation of the builtintest. If you are interested in details of the differences of the systemtestand the shell builtintestthen you can read the debian developer discussion here: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267142.