25.03.2013 Views

Copyright Sams Teach Yourself Shell Programming in 24 Hours

Copyright Sams Teach Yourself Shell Programming in 24 Hours

Copyright Sams Teach Yourself Shell Programming in 24 Hours

SHOW MORE
SHOW LESS

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

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

77 if [ $? -ne 0 ] ; then<br />

78 pr<strong>in</strong>tERROR "Unable to successfully move $1 to $2"<br />

79 fi<br />

80<br />

81 # if a rename of the copy is requested<br />

82<br />

83 if [ -n "$NEWNAME" ] ; then<br />

84<br />

85 # try and change to the dest<strong>in</strong>ation directory<br />

86<br />

87 cd "$DESTDIR" > /dev/null 2>&1<br />

88 if [ $? -ne 0 ] ; then<br />

89 pr<strong>in</strong>tERROR "Could not cd to $DESTDIR"<br />

90 fi<br />

91<br />

92 # try and rename the copy<br />

93<br />

94 /b<strong>in</strong>/mv "$SRCDIR_CHILD" "$NEWNAME" > /dev/null 2>&1<br />

95 if [ $? -ne 0 ] ; then<br />

96 pr<strong>in</strong>tERROR "Could not rename $1 to $2"<br />

97 fi<br />

98<br />

99 # return to the orig<strong>in</strong>al directory<br />

100<br />

101 cd "$SRCDIR_PARENT" > /dev/null 2>&1<br />

102 if [ $? -ne 0 ] ; then<br />

103 pr<strong>in</strong>tERROR "Could not cd to $SRCDIR_PARENT"<br />

104 fi<br />

105 fi<br />

106<br />

107 # try and remove the orig<strong>in</strong>al<br />

108<br />

109 if [ -d "$SRCDIR_CHILD" ] ; then<br />

110 /b<strong>in</strong>/rm -r "$SRCDIR_CHILD" > /dev/null 2>&1<br />

111 if [ $? -ne 0 ] ; then<br />

112 pr<strong>in</strong>tERROR "Could not remove $1"<br />

113 fi<br />

114 fi<br />

115<br />

116 exit 0<br />

A Walkthrough of mvdir.sh<br />

I'll walk through the script and highlight some of the important po<strong>in</strong>ts.<br />

The first th<strong>in</strong>g this script does is set the PATH variable (l<strong>in</strong>e 7). You do this to ensure that all the commands<br />

you use come from one of the two directories that you specified. When you write a script that can be run by<br />

many users, you have to take <strong>in</strong>to account that some users might have modified their PATH such that the<br />

commands you are us<strong>in</strong>g are <strong>in</strong>accessible or replaced by other versions. By sett<strong>in</strong>g the PATH variable<br />

explicitly, you avoid this problem.<br />

Next the script def<strong>in</strong>es a few utility functions (l<strong>in</strong>es 11 and 15) used to pr<strong>in</strong>t error usage messages. You can

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

Saved successfully!

Ooh no, something went wrong!