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.

Chapter 32. Gotchas<br />

Turandot: Gli enigmi sono tre, la morte una!<br />

Caleph: No, no! Gli enigmi sono tre, una la vita!<br />

Puccini<br />

Assigning reserved words or characters to variable names.<br />

case=value0 # Causes problems.<br />

23skidoo=value1 # Also problems.<br />

# Variable names starting with a digit are reserved by the shell.<br />

# Try _23skidoo=value1. Starting variables with an underscore is o.k.<br />

# However... using just the underscore will not work.<br />

_=25<br />

echo $_<br />

# $_ is a special variable set to last arg of last command.<br />

xyz((!*=value2<br />

# Causes severe problems.<br />

Using a hyphen or other reserved characters in a variable name.<br />

var−1=23<br />

# Use 'var_1' instead.<br />

Using the same name for a variable and a function. This can make a script difficult to understand.<br />

do_something ()<br />

{<br />

echo "This function does something with \"$1\"."<br />

}<br />

do_something=do_something<br />

do_something do_something<br />

# All this is legal, but highly confusing.<br />

Using whitespace inappropriately. In contrast to other programming languages, Bash can be quite finicky<br />

about whitespace.<br />

var1 = 23 # 'var1=23' is correct.<br />

# On line above, Bash attempts to execute command "var1"<br />

# with the arguments "=" and "23".<br />

let c = $a − $b<br />

# 'let c=$a−$b' or 'let "c = $a − $b"' are correct.<br />

if [ $a −le 5] # if [ $a −le 5 ] is correct.<br />

# if [ "$a" −le 5 ] is even better.<br />

# [[ $a −le 5 ]] also works.<br />

Assuming uninitialized variables (variables before a value is assigned to them) are "zeroed out". An<br />

uninitialized variable has a value of "null", not zero.<br />

#!/bin/bash<br />

Chapter 32. Gotchas 327

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

Saved successfully!

Ooh no, something went wrong!