In this example, $1 would refer to cdrom/, and $2 would refer to dir1/.

Another thing that prevented me from writing good scripts was not knowing how to process command-line flags like scriptname -q file1.txt. Thus, if a script I wanted to write was sophisticated enough to need command-line flags, I would use a different language or not write it at all. It turns out bash has a feature called getopt that does all the parsing for you, but the manual page for Bash isn't clear. It tells you how the getopt function works, but not how to use it. Finally, I found an example of how to use it and have been copying that example time and time again. It isn't important how it works; you don't even have to understand how it works or why it works to use it. You use it like this: args='getopt ab: $*' if [ $? != 0 ] then echo 'Usage: command [-a] [-b file.txt] file1 file2 ...' exit -1 fi set -- $args for i do case '$i' in -a) FLAGA=1 shift ;; -b) ITEMB='$2' ; shift shift ;; --) shift; break ;; esac done

This would be a command that has flags -a and -b. -b is special because it must be followed by an argument such as -b file.txt. It you look at the first line, the getopt command is followed by the letters that can be flags. There is a colon after any letter that requires an additional argument. Later, we see a case statement for each possible argument, with code that either sets a flag or sets a flag and remembers the argument.

What is this $2 business? What's the deal with the —)? What does set - mean? And what about Naomi? Those are all things you can look up later. Just follow the template and it all works.

(OK, if you really want to learn why all of that works, I highly recommend reading the Advanced Bash-Scripting Guide at http://www.tldp.org/LDP/abs/html.)

Here's a larger example that adds a couple additional things. First of all, it uses a function 'usage' to print out the help message. An interesting thing about this function is that the 'echo' lasts multiple lines. Neat, eh? Bash doesn't mind. Second, it makes sure that there are at least MINITEMS items on the command line after the options are processed. Finally, it demonstrates how to process flags that override defaults.

Please steal this code whenever you are turning a simple script into one that takes options and parameters: #!/bin/bash MINITEMS=1 function usage { echo ' Usage: $0 [-d] [-a author] [-c file.txt] [-h] dir1 [dir1 ...] -d debug, don't actual run command -a author name of the author -c copyright override default copyright file -h this help message ' exit 1 } # Set our defaults: DEBUG=false DEBUGCMD= AUTHOR= COPYRIGHT=copyright.txt # Process command-line arguments, possibly overriding defaults args='getopt da:c:h $*' if [ $? != 0 ] then usage fi set -- $args for i do

Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату