Arithmetic and logical binary operators in shell programming

Arithmetic operators calculate numeric values. You can use one or more arithmetic operators to add, subtract, multiply, and divide values, and to calculate the remainder modulus of a division operation. The addition operator concatenates the input. The multiplication operator returns multiple copies of the input. You can even mix object types in an arithmetic statement.

The method that is used to evaluate the statement is determined by the type of the leftmost object in the expression. Beginning in PowerShell 3. PowerShell processes the expressions from left to right according to the precedence rules. The following examples show the effect of the precedence rules:. The order in which PowerShell evaluates expressions might differ from other programming and scripting languages that you have used. The following example shows a complicated assignment statement.

When the quotient of a division operation is an integer, PowerShell rounds the value to the nearest integer. When the value is. You can add numbers, strings, arrays, and hash tables.

And, you can multiply numbers, strings, and arrays. However, you cannot multiply hash tables. When you add strings, arrays, or hash tables, the elements are concatenated. When you concatenate collections, such as arrays or hash tables, a new object is created that contains the objects from both collections.

If you try to concatenate hash tables that have the same key, the operation fails. You can also perform arithmetic operations on objects of different types. The operation that PowerShell performs is determined by the Microsoft. NET Framework type of the leftmost object in the operation.

PowerShell tries to convert all the objects in the operation to the. NET Framework type of the first object. If it succeeds in converting the objects, it performs the operation appropriate to the. If it fails to convert any of the objects, the operation fails.

The following examples demonstrate the use of the addition and multiplication operators; in operations that include different object types. Because the method that is used to evaluate statements is determined by the leftmost object, addition and multiplication in PowerShell are not strictly commutative. Hash tables are a slightly different case. You can add hash tables to another hash table, as long as, the added hash tables don't have duplicate keys.

Also, you can add a hash table to an array; and, the entire hash table becomes an item in the array. Although the addition operators are very useful, use the assignment operators to add elements to hash tables and arrays. PowerShell automatically selects the. NET Framework numeric type that best expresses the result without losing precision. If the result of an operation is too large for the type, the type of the result is widened to accommodate the result, as in the following example:.

The type of the result will not necessarily be the same as one of the operands. In the following example, the negative value cannot be cast to an unsigned integer, and the unsigned integer is too large to be cast to Int Decimal type is an exception.

If either operand has the Decimal type, the result will be of the Decimal type. If the result is too large for the Decimal type, it will not be cast to Double.

Instead, an error results. You can also use arithmetic operators with variables. The shell return code negation operator! You cannot use them inside test expressions. Use -a and -o to separate Boolean clauses to the test command:. Above, the separates two different and complete test command executions.

Rather than using the test command twice, you can simply join them into one using the correct test Boolean operator:. The test helper command has six ways to compare numbers and two ways to compare strings. Boolan logic has some subtle consequences when applied to the operations performed by the test helper command. These are all correct opposites. The logical opposite of the test operator -lt less than is not -gt greater than , it is -ge greater than or equal to.

If you are not younger than your sister, you are either older or the same age. The opposite of the test operator -gt is not -lt , it is -le. The test operators -f and -d are not opposites. If a pathname is not a file, it may or may not be a directory. It could be a directory or any number of other special file types under Unix. The test pathname operators all return success zero only if the pathname is accessible all the directories can be traversed AND the pathname exists AND if it has the given pathname property.

You need to apply more programming logic if you want to know that a pathname actually exists but is not, for example, readable:. Remember that inverting a pathname test may mean the inverted test succeeds because the pathname is not accessible or does not exist!

If a test pathname operator e. Without first testing if you can access the pathname and that it actually exists, the following error message is misleading:. While it is true that the pathname is not readable, the above error message is incomplete. You might not have permission to traverse all the directories in its pathname, or, the pathname might not even exist. Saying the overall pathname is not readable is true, but it is only part of the truth.

A more accurate error message would be:. If you want to be more specific in your error message about why the pathname is not readable, you need code to test for existence first:. The test for readability is now done only if the pathname exists and is accessible; if the test for readability fails, you know the existing, accessible pathname item is truly not readable.

The error message is more accurate now. Any time one of the test pathname operator tests fails, be accurate in your error message. State whether the failure is due to a missing or inaccessible pathname, or due to a failure of the actual test being performed on the existing, accessible pathname. Be careful in if statements when testing multiple conditions at the same time that you do not make the failure error message unhelpful:.

The error would have to read like this: Which failure was it? Such a complex error message is not helpful to the users of your scripts! The programmer forgot that the if statement can directly test the return code of the command it executes.

Calling up the test command to examine the shell variable for the return code of the previous command is superfluous.

Plain Text - plain text version of this page in Pandoc Markdown format. Shell Script Problems — arithmetic, syntax, test, boolean, etc. Allen — idallen idallen. For example, having a missing or non-integer argument to the test command may produce a vague error message: Running the script using a shell with the debug options -x or -v set may also be helpful: This line below is wrong thinking; it forgets to use the test helper program: Always remember to code some Unix command name after if: The above syntactic-sugar line is equivalent to this also incorrect line: If you want to test the return status of grep , grep must be the command name that immediately follows the if keyword: The following code does not work; because, blanks are missing around the first square bracket, making it into an unknown command named [1: The following incorrect statement fails for the same reason: Always use blanks around [ and ]: This next line fails because of the missing blank before the required closing square bracket: The corrected line uses blanks: The following one-argument tests are always TRUE, though they may not appear that way at first to human eyes: The shell is actually executing these tests: If you want to perform equality tests, you must separate each argument by blanks so that test sees three separate arguments, not just one: