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

#!/bin/bash<br />

echo $_<br />

du >/dev/null<br />

echo $_<br />

ls −al >/dev/null<br />

echo $_<br />

# /bin/bash<br />

# Just called /bin/bash to run the script.<br />

# So no output from command.<br />

# du<br />

# So no output from command.<br />

# −al (last argument)<br />

$?<br />

$$<br />

:<br />

echo $_ # :<br />

Exit status of a command, function, or the script itself (see Example 23−3)<br />

Process id of the script itself. The $$ variable often finds use in scripts to construct "unique" temp file<br />

names (see Example A−14, Example 30−6, Example 12−23, and Example 11−23). This is usually<br />

simpler than invoking mktemp.<br />

9.2. Manipulating Strings<br />

Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unified<br />

focus. Some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr<br />

command. This results in inconsistent command syntax and overlap of functionality, not to mention<br />

confusion.<br />

String Length<br />

${#string}<br />

expr length $string<br />

expr "$string" : '.*'<br />

stringZ=abcABC123ABCabc<br />

echo ${#stringZ} # 15<br />

echo `expr length $stringZ` # 15<br />

echo `expr "$stringZ" : '.*'` # 15<br />

Example 9−10. Inserting a blank line between paragraphs in a text file<br />

#!/bin/bash<br />

# paragraph−space.sh<br />

# Inserts a blank line between paragraphs of a single−spaced text file.<br />

# Usage: $0

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

Saved successfully!

Ooh no, something went wrong!