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.

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

var01=abcdEFGH28ij<br />

echo "var01 = ${var01}"<br />

echo "Length of var01 = ${#var01}"<br />

echo "Number of command−line arguments passed to script = ${#@}"<br />

echo "Number of command−line arguments passed to script = ${#*}"<br />

exit 0<br />

${var#Pattern}, ${var##Pattern}<br />

Remove from $var the shortest/longest part of $Pattern that matches the front end of $var.<br />

A usage illustration from Example A−8:<br />

# Function from "days−between.sh" example.<br />

# Strips leading zero(s) from argument passed.<br />

strip_leading_zero () # Better to strip possible leading zero(s)<br />

{ # from day and/or month<br />

val=${1#0}<br />

# since otherwise Bash will interpret them<br />

return $val # as octal values (POSIX.2, sect 2.9.2.1).<br />

}<br />

Another usage illustration:<br />

echo `basename $PWD`<br />

echo "${PWD##*/}"<br />

echo<br />

echo `basename $0`<br />

echo $0<br />

echo "${0##*/}"<br />

echo<br />

filename=test.data<br />

echo "${filename##*.}"<br />

# Basename of current working directory.<br />

# Basename of current working directory.<br />

# Name of script.<br />

# Name of script.<br />

# Name of script.<br />

# data<br />

# Extension of filename.<br />

${var%Pattern}, ${var%%Pattern}<br />

Remove from $var the shortest/longest part of $Pattern that matches the back end of $var.<br />

Version 2 of Bash adds additional options.<br />

Example 9−16. Pattern matching in parameter substitution<br />

#!/bin/bash<br />

# Pattern matching using the # ## % %% parameter substitution operators.<br />

var1=abcd12345abc6789<br />

pattern1=a*c # * (wild card) matches everything between a − c.<br />

echo<br />

echo "var1 = $var1"<br />

# abcd12345abc6789<br />

echo "var1 = ${var1}" # abcd12345abc6789 (alternate form)<br />

echo "Number of characters in ${var1} = ${#var1}"<br />

echo "pattern1 = $pattern1" # a*c (everything between 'a' and 'c')<br />

echo<br />

Chapter 9. Variables Revisited 88

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

Saved successfully!

Ooh no, something went wrong!