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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

command1 2> − | command2 # Trying to redirect error output of command1 into a pipe...<br />

# ...will not work.<br />

command1 2>& − | command2 # Also futile.<br />

Thanks, S.C.<br />

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

Using Bash version 2+ functionality may cause a bailout with error messages. Older Linux machines may<br />

have version 1.XX of Bash as the default installation.<br />

#!/bin/bash<br />

minimum_version=2<br />

# Since Chet Ramey is constantly adding features to Bash,<br />

# you may set $minimum_version to 2.XX, or whatever is appropriate.<br />

E_BAD_VERSION=80<br />

if [ "$BASH_VERSION" \< "$minimum_version" ]<br />

then<br />

echo "This script works only with Bash, version $minimum or greater."<br />

echo "Upgrade strongly recommended."<br />

exit $E_BAD_VERSION<br />

fi<br />

...<br />

Using Bash−specific functionality in a Bourne shell script (#!/bin/sh) on a non−Linux machine may cause<br />

unexpected behavior. A Linux system usually aliases sh to bash, but this does not necessarily hold true for a<br />

generic UNIX machine.<br />

A script with DOS−type newlines (\r\n) will fail to execute, since #!/bin/bash\r\n is not recognized,<br />

not the same as the expected #!/bin/bash\n. The fix is to convert the script to UNIX−style newlines.<br />

#!/bin/bash<br />

echo "Here"<br />

unix2dos $0<br />

chmod 755 $0<br />

# Script changes itself to DOS format.<br />

# Change back to execute permission.<br />

# The 'unix2dos' command removes execute permission.<br />

./$0 # Script tries to run itself again.<br />

# But it won't work as a DOS file.<br />

echo "There"<br />

exit 0<br />

A shell script headed by #!/bin/sh may not run in full Bash−compatibility mode. Some Bash−specific<br />

functions might be disabled. Scripts that need complete access to all the Bash−specific extensions should start<br />

with #!/bin/bash.<br />

A script may not export variables back to its parent process, the shell, or to the environment. Just as we<br />

learned in biology, a child process can inherit from a parent, but not vice versa.<br />

WHATEVER=/home/bozo<br />

export WHATEVER<br />

Chapter 32. Gotchas 329

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

Saved successfully!

Ooh no, something went wrong!