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...

Create successful ePaper yourself

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

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

# Conversion to bash v2 syntax done by Chet Ramey<br />

# Commentary:<br />

# Code:<br />

#:docstring strcat:<br />

# Usage: strcat s1 s2<br />

#<br />

# Strcat appends the value of variable s2 to variable s1.<br />

#<br />

# Example:<br />

# a="foo"<br />

# b="bar"<br />

# strcat a b<br />

# echo $a<br />

# => foobar<br />

#<br />

#:end docstring:<br />

###;;;autoload ==> Autoloading of function commented out.<br />

function strcat ()<br />

{<br />

local s1_val s2_val<br />

}<br />

s1_val=${!1}<br />

# indirect variable expansion<br />

s2_val=${!2}<br />

eval "$1"=\'"${s1_val}${s2_val}"\'<br />

# ==> eval $1='${s1_val}${s2_val}' avoids problems,<br />

# ==> if one of the variables contains a single quote.<br />

#:docstring strncat:<br />

# Usage: strncat s1 s2 $n<br />

#<br />

# Line strcat, but strncat appends a maximum of n characters from the value<br />

# of variable s2. It copies fewer if the value of variabl s2 is shorter<br />

# than n characters. Echoes result on stdout.<br />

#<br />

# Example:<br />

# a=foo<br />

# b=barbaz<br />

# strncat a b 3<br />

# echo $a<br />

# => foobar<br />

#<br />

#:end docstring:<br />

###;;;autoload<br />

function strncat ()<br />

{<br />

local s1="$1"<br />

local s2="$2"<br />

local −i n="$3"<br />

local s1_val s2_val<br />

s1_val=${!s1}<br />

s2_val=${!s2}<br />

if [ ${#s2_val} −gt ${n} ]; then<br />

s2_val=${s2_val:0:$n}<br />

fi<br />

# ==> indirect variable expansion<br />

# ==> substring extraction<br />

Appendix A. Contributed Scripts 392

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

Saved successfully!

Ooh no, something went wrong!