24.07.2018 Views

Bash-Beginners-Guide

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

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

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

The opposite effect is obtained using "%" and "%%", as in this example below. WORD should match a trailing<br />

portion of string:<br />

[bob in ~] echo $STRING<br />

thisisaverylongname<br />

[bob in ~] echo ${STRING%name}<br />

thisisaverylong<br />

10.3.3.3. Replacing parts of variable names<br />

This is done using the<br />

${VAR/PATTERN/STRING}<br />

or<br />

${VAR//PATTERN/STRING}<br />

syntax. The first form replaces only the first match, the second replaces all matches of PATTERN with<br />

STRING:<br />

[bob in ~] echo ${STRING/name/string}<br />

thisisaverylongstring<br />

More information can be found in the <strong>Bash</strong> info pages.<br />

10.4. Summary<br />

Normally, a variable can hold any type of data, unless variables are declared explicitly. Constant variables are<br />

set using the readonly built-in command.<br />

An array holds a set of variables. If a type of data is declared, then all elements in the array will be set to hold<br />

only this type of data.<br />

<strong>Bash</strong> features allow for substitution and transformation of variables "on the fly". Standard operations include<br />

calculating the length of a variable, arithmetic on variables, substituting variable content and substituting part<br />

of the content.<br />

10.5. Exercises<br />

Here are some brain crackers:<br />

1. Write a script that does the following:<br />

♦ Display the name of the script being executed.<br />

♦ Display the first, third and tenth argument given to the script.<br />

♦ Display the total number of arguments passed to the script.<br />

♦ If there were more than three positional parameters, use shift to move all the values 3 places<br />

to the left.<br />

♦ Print all the values of the remaining arguments.<br />

Chapter 10. More on variables 129

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

Saved successfully!

Ooh no, something went wrong!