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

echo "Arg #$index = $arg"<br />

let "index+=1"<br />

done<br />

# $@ sees arguments as separate words.<br />

echo "Arg list seen as separate words."<br />

echo<br />

exit 0<br />

Following a shift, the $@ holds the remaining command−line parameters, lacking the previous $1,<br />

which was lost.<br />

#!/bin/bash<br />

# Invoke with ./scriptname 1 2 3 4 5<br />

echo "$@" # 1 2 3 4 5<br />

shift<br />

echo "$@" # 2 3 4 5<br />

shift<br />

echo "$@" # 3 4 5<br />

# Each "shift" loses parameter $1.<br />

# "$@" then contains the remaining parameters.<br />

The $@ special parameter finds use as a tool for filtering input into shell scripts. The cat "$@"<br />

construction accepts input to a script either from stdin or from files given as parameters to the<br />

script. See Example 12−17 and Example 12−18.<br />

The $* and $@ parameters sometimes display inconsistent and puzzling behavior,<br />

depending on the setting of $IFS.<br />

Example 9−7. Inconsistent $* and $@ behavior<br />

#!/bin/bash<br />

# Erratic behavior of the "$*" and "$@" internal Bash variables,<br />

#+ depending on whether they are quoted or not.<br />

# Inconsistent handling of word splitting and linefeeds.<br />

set −− "First one" "second" "third:one" "" "Fifth: :one"<br />

# Setting the script arguments, $1, $2, etc.<br />

echo<br />

echo 'IFS unchanged, using "$*"'<br />

c=0<br />

for i in "$*"<br />

# quoted<br />

do echo "$((c+=1)): [$i]"<br />

done<br />

echo −−−<br />

echo 'IFS unchanged, using $*'<br />

c=0<br />

for i in $*<br />

# unquoted<br />

do echo "$((c+=1)): [$i]"<br />

# This line remains the same in every instance.<br />

# Echo args.<br />

Chapter 9. Variables Revisited 75

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

Saved successfully!

Ooh no, something went wrong!