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.

#+ it is necessary to substitute for the normal "/" delimiter<br />

#+ because "/" happens to be one of the characters filtered out.<br />

# Failure to do so gives an error message (try it).<br />

done<br />

exit 0<br />

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

# Exercise (easy):<br />

# −−−−−−−−−−−−−−−<br />

# Convert this script to taking command−line parameters<br />

#+ for $directory and $fstring.<br />

The output of a for loop may be piped to a command or commands.<br />

Example 10−10. Listing the symbolic links in a directory<br />

#!/bin/bash<br />

# symlinks.sh: Lists symbolic links in a directory.<br />

directory=${1−`pwd`}<br />

# Defaults to current working directory,<br />

#+ if not otherwise specified.<br />

# Equivalent to code block below.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# ARGS=1 # Expect one command−line argument.<br />

#<br />

# if [ $# −ne "$ARGS" ] # If not 1 arg...<br />

# then<br />

# directory=`pwd` # current working directory<br />

# else<br />

# directory=$1<br />

# fi<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

echo "symbolic links in directory \"$directory\""<br />

for file in "$( find $directory −type l )"<br />

do<br />

echo "$file"<br />

done | sort<br />

# −type l = symbolic links<br />

# Otherwise file list is unsorted.<br />

# As Dominik 'Aeneas' Schnitzer points out,<br />

#+ failing to quote $( find $directory −type l )<br />

#+ will choke on filenames with embedded whitespace.<br />

# Even this will only pick up the first field of each argument.<br />

exit 0<br />

The stdout of a loop may be redirected to a file, as this slight modification to the previous example<br />

shows.<br />

Example 10−11. Symbolic links in a directory, saved to a file<br />

#!/bin/bash<br />

# symlinks.sh: Lists symbolic links in a directory.<br />

Chapter 10. Loops and Branches 108

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

Saved successfully!

Ooh no, something went wrong!