27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The multiplication operator must be escaped when used in an arithmetic expression with<br />

expr.<br />

y=`expr $y + 1`<br />

Increment a variable, with the same effect as let y=y+1 and y=$(($y+1)). This is an<br />

example of arithmetic expansion.<br />

z=`expr substr $string $position $length`<br />

Extract substring of $length characters, starting at $position.<br />

Example 12−6. Using expr<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

#!/bin/bash<br />

# Demonstrating some of the uses of 'expr'<br />

# =======================================<br />

echo<br />

# Arithmetic Operators<br />

# −−−−−−−−−− −−−−−−−−−<br />

echo "Arithmetic Operators"<br />

echo<br />

a=`expr 5 + 3`<br />

echo "5 + 3 = $a"<br />

a=`expr $a + 1`<br />

echo<br />

echo "a + 1 = $a"<br />

echo "(incrementing a variable)"<br />

a=`expr 5 % 3`<br />

# modulo<br />

echo<br />

echo "5 mod 3 = $a"<br />

echo<br />

echo<br />

# Logical Operators<br />

# −−−−−−− −−−−−−−−−<br />

# Returns 1 if true, 0 if false,<br />

#+ opposite of normal Bash convention.<br />

echo "Logical Operators"<br />

echo<br />

x=24<br />

y=25<br />

b=`expr $x = $y`<br />

# Test equality.<br />

echo "b = $b" # 0 ( $x −ne $y )<br />

echo<br />

a=3<br />

b=`expr $a \> 10`<br />

echo 'b=`expr $a \> 10`, therefore...'<br />

echo "If a > 10, b = 0 (false)"<br />

echo "b = $b" # 0 ( 3 ! −gt 10 )<br />

echo<br />

Chapter 12. External Filters, Programs and Commands 155

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!