# Scripting with zsh Shell Scripting

The main purpose of the zsh shell was to provide an advanced programming environment forshell programmers. With that in mind, it’s no surprise that the zsh shell offers many features that make shell scripting easier. Mathematical operations

As you would expect, the zsh shell allows you to perform mathematical functions with ease. Similarto the ksh93 shell, the zsh shell has full support for floating-point numberin all of its mathematical operations. Performing calculations The zsh shell supports the same two methods for performing mathematical operations as theksh93 shell:

• The let command
• Double parentheses

When you use the let command you should enclose the operation in double quotation marks to allow for spaces:

% let value1=" 4 * 5.1 / 3.2 "
% echo $value1 6.3749999999999991 % Notice that using floating point numbers introduces a precision problem. To solve this, it’s alwaysa good idea to use the printf command, and specify the decimal precision needed to correctlydisplay the answer: The second method is to use the double parentheses. This method incorporates two techniques fordefining the mathematical operation: Notice that you can place the double parentheses either around just the operation (preceded by adollar sign) or around the entire assignment statement. Both methods produce the same results. If you don’t use the typeset command to declare the data type of a variable beforehand, the zshshell attempts to automatically assign the data type. This can be dangerous when working with both integer and floating-point numbers. Take a look at this example: % value=10 % value2=$(( $value1 / 3 )) % echo$value2
3
%

Now that’s probably not the answer you want to come out from the calculation. When you specify numberswithout decimal places, the zsh shell interprets them as integer values, and performsinteger calculations. To ensure that the result is a floating point number, you must specify the numbers with decimal places:

% value=10.
% value2=$(($value1 / 3. ))
% echo $value2 3.3333333333333335 % Now the result is in the floating point format.Mathematical functions With the zsh shell, built-in mathematical functions are either feast or famine. The default zsh shell doesn’t include any special mathematical function.However, if you install the zsh/mathfuncmodule, you’ll have more math functions than you’ll most likely ever need: % value1=$(( sqrt(9) ))
zsh: unknown function: sqrt
% value1=$(( sqrt(9) )) % echo$value1
3.
%

intf "%6.3f " $value1 6.375 % Now that’s much better! This also applies to shell scripts. If you have a function you need to use, you’ll need to use the auto load command to make sure that it’s available: % cat test4 #!/bin/zsh # testing an external function autoload dbl dbl$1