24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[bob in testdir] export TESTVAR=present<br />

[bob in testdir] ./vartest.sh<br />

present<br />

TESTVAR is set, we can proceed.<br />

Using "+" instead of the exclamation mark sets the variable to the expansion of WORD; if it does not exist,<br />

nothing happens.<br />

10.3.3.2. Removing substrings<br />

To strip a number of characters, equal to OFFSET, from a variable, use this syntax:<br />

${VAR:OFFSET:LENGTH}<br />

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

The LENGTH parameter defines how many characters to keep, starting from the first character after the offset<br />

point. If LENGTH is omitted, the remainder of the variable content is taken:<br />

[bob in ~] export STRING="thisisaverylongname"<br />

[bob in ~] echo ${STRING:4}<br />

isaverylongname<br />

[bob in ~] echo ${STRING:6:5}<br />

avery<br />

${VAR#WORD}<br />

and<br />

${VAR##WORD}<br />

These constructs are used for deleting the pattern matching the expansion of WORD in VAR. WORD is expanded<br />

to produce a pattern just as in file name expansion. If the pattern matches the beginning of the expanded value<br />

of VAR, then the result of the expansion is the expanded value of VAR with the shortest matching pattern ("#")<br />

or the longest matching pattern (indicated with "##").<br />

If VAR is * or @, the pattern removal operation is applied to each positional parameter in turn, and the<br />

expansion is the resultant list.<br />

If VAR is an array variable subscribed with "*" or "@", the pattern removal operation is applied to each<br />

member of the array in turn, and the expansion is the resultant list. This is shown in the examples below:<br />

[bob in ~] echo ${ARRAY[*]}<br />

one two one three one four<br />

[bob in ~] echo ${ARRAY[*]#one}<br />

two three four<br />

[bob in ~] echo ${ARRAY[*]#t}<br />

one wo one hree one four<br />

[bob in ~] echo ${ARRAY[*]#t*}<br />

one wo one hree one four<br />

[bob in ~] echo ${ARRAY[*]##t*}<br />

one one one four<br />

Chapter 10. More on variables 128

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

Saved successfully!

Ooh no, something went wrong!