Test operators (?)

The test operator can be used in a few different scenarios. We already saw in the parameter substitution that it is used to check whether a variable has a value or not. In arithmetic operations, it can be used to implement the trinary or ternary operator in a C-style notation:

#!/bin/bash
x=20
y=30
w=40
z=50
k=100
echo 'Usually you would write a control loop in the following way:'
echo 'if [[ $x -gt $y ]]'
echo ' then'
echo ' z="$w"'
echo ' echo "The value for z is: $z"'
echo ' else'
echo ' z="$k"'
echo ' echo "The value for z is: $z"'
echo 'fi'
if [[ $x -gt $y ]]
then
z="$w"
echo "The value for z is: $z"
else
z="$k"
echo "The value for z is: $z"
fi
echo 'But you can also use the C-style trinary operator to achieve the same result:'
echo '(( z = x>y?w:k ))'
echo 'echo "The value for z is: $z"'
(( z = x>y?w:k ))
echo "The value for z is: $z"

As you can see, the C-style notation is more compact even though it is not as readable as a standard loop notation. Let's try it here:

zarrelli:~$ ./c-style.sh

Usually, you would write a control loop in the following way:

if [[ $x -gt $y ]]
then
z="$w"
echo "The value for z is: "$z""
else
z="$k"
echo "The value for z is: "$z""
fi
The value for z is: 100

But you can also use the C-style trinary operator to achieve the same result:

(( z = x>y?w:k ))
echo "The value for z is: $z"
The value for z is: 100

As you can see, we reached the same result but with a more compact code. Essentially, we give a condition that ends with the ? character and then, alternative results follow, which are separated by a : character.

We see that the C-style is widely used in loops and can be defined as a compound command used to evaluate mathematical expressions in a loop, and as seen in the previous example, assign a variable. It is made of three blocks: the first initializes a variable before the first iteration, the second checks for a condition that exits the look, and the third modifies the initial condition. Sounds strange? Look at this, it will look really familiar:

#!/bin/bash
for ((i = 0 ; i < 3 ; i++)); do
echo "Counting loop number $i"
done

Now, let's execute it:

zarrelli:~$ ./c-style-counter.sh
Counting loop number 0
Counting loop number 1
Counting loop number 2

Finally, you can find the quotation mark used for file name expansion in globbing as a wild card matching any one characters; in regular expressions, use it as a single character match.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.96