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

# ==> Comments added by author of this document.<br />

HERE=`uname −n` # ==> hostname<br />

THERE=bilbo<br />

echo "starting remote backup to $THERE at `date +%r`"<br />

# ==> `date +%r` returns time in 12−hour format, i.e. "08:08:34 PM".<br />

# make sure /pipe really is a pipe and not a plain file<br />

rm −rf /pipe<br />

mkfifo /pipe # ==> Create a "named pipe", named "/pipe".<br />

# ==> 'su xyz' runs commands as user "xyz".<br />

# ==> 'ssh' invokes secure shell (remote login client).<br />

su xyz −c "ssh $THERE \"cat >/home/xyz/backup/${HERE}−daily.tar.gz\" < /pipe"&<br />

cd /<br />

tar −czf − bin boot dev etc home info lib man root sbin share usr var >/pipe<br />

# ==> Uses named pipe, /pipe, to communicate between processes:<br />

# ==> 'tar/gzip' writes to /pipe and 'ssh' reads from /pipe.<br />

# ==> The end result is this backs up the main directories, from / on down.<br />

# ==> What are the advantages of a "named pipe" in this situation,<br />

# ==> as opposed to an "anonymous pipe", with |?<br />

# ==> Will an anonymous pipe even work here?<br />

exit 0<br />

+<br />

Stephane Chazelas contributed the following script to demonstrate that generating prime numbers does not<br />

require arrays.<br />

Example A−17. Generating prime numbers using the modulo operator<br />

#!/bin/bash<br />

# primes.sh: Generate prime numbers, without using arrays.<br />

# Script contributed by Stephane Chazelas.<br />

# This does *not* use the classic "Sieve of Eratosthenes" algorithm,<br />

#+ but instead uses the more intuitive method of testing each candidate number<br />

#+ for factors (divisors), using the "%" modulo operator.<br />

LIMIT=1000 # Primes 2 − 1000<br />

Primes()<br />

{<br />

(( n = $1 + 1 )) # Bump to next integer.<br />

shift<br />

# Next parameter in list.<br />

# echo "_n=$n i=$i_"<br />

if (( n == LIMIT ))<br />

then echo $*<br />

return<br />

fi<br />

Appendix A. Contributed Scripts 389

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

Saved successfully!

Ooh no, something went wrong!