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 "Part 2 of script."<br />

echo $a # Value of $a stays at 1.<br />

[6] This allows some cute tricks.<br />

#!/bin/rm<br />

# Self−deleting script.<br />

# Nothing much seems to happen when you run this... except that the file disappears.<br />

WHATEVER=65<br />

echo "This line will never print (betcha!)."<br />

exit $WHATEVER # Doesn't matter. The script will not exit here.<br />

Also, try starting a README file with a #!/bin/more, and making it executable. The result is a<br />

self−listing documentation file.<br />

[7] Portable Operating System Interface, an attempt to standardize UNIX−like OSes.<br />

[8] Caution: invoking a Bash script by sh scriptname turns off Bash−specific extensions, and the<br />

script may therefore fail to execute.<br />

[9] A script needs read, as well as execute permission for it to run, since the shell needs to be able to read<br />

it.<br />

[10] Why not simply invoke the script with scriptname? If the directory you are in ($PWD) is where<br />

scriptname is located, why doesn't this work? This fails because, for security reasons, the current<br />

directory, "." is not included in a user's $PATH. It is therefore necessary to explicitly invoke the script<br />

in the current directory with a ./scriptname.<br />

[11] The shell does the brace expansion. The command itself acts upon the result of the expansion.<br />

[12] Exception: a code block in braces as part of a pipe may be run as a subshell.<br />

ls | { read firstline; read secondline; }<br />

# Error. The code block in braces runs as a subshell,<br />

# so the output of "ls" cannot be passed to variables within the block.<br />

echo "First line is $firstline; second line is $secondline" # Will not work.<br />

# Thanks, S.C.<br />

[13] The process calling the script sets the $0 parameter. By convention, this parameter is the name of the<br />

script. See the manpage for execv.<br />

[14] Encapsulating "!" within double quotes gives an error when used from the command line. Apparently<br />

this is interpreted as a history command. Within a script, though, this problem does not occur.<br />

Of more concern is the inconsistent behavior of "\" within double quotes.<br />

bash$ echo hello\!<br />

hello!<br />

bash$ echo "hello\!"<br />

hello\!<br />

Appendix J. Copyright 441

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

Saved successfully!

Ooh no, something went wrong!