Вы находитесь на странице: 1из 8

Bash shell scripting

1. Scripting files Just create a text file and put commands in it. No special extension is needed. Then make it executable. file: numJava # How many Java source files are in the directory # that the user specifies? cd $1 ls *.java | wc -l $ nano numJava $ chmod 700 numJava $ ./numJava # create the file # make it executable by you # run it

If . is in your path, then you do simply: $ numJava # run it

If you do not wish to make the shell script file executable because of security concerns, you can still run it by putting the command bash in front: $ bash numJava # run it

As you can see, comments in bash are introduced by the sharp sign. You can use them in both regular commands that you type at the keyboard or in a shell script. There are no C-style comments, i.e. no multi-line comments. Command line arguments are denoted by $1, $2, $3, etc. The command name itself is $0. The number of arguments is given by $#.

2. If statements Bash syntax is a little weird, and unlike C or Java. Heres the basic format: if [ condition ]; then fi if [ condition ]; then else fi if [ condition1 ]; then elif [ condition2 ]; then elif [ condition3 ]; then else fi The body of the if (represented by 3 dots above) can be anything, including other if statements. The conditions fall into two basic types: integers and strings. (There are no real numbers in bash.) Unfortunately, they use two different sets of comparators: equals not equals less than less than or equal to greater than greater than or equal to integer -eq -ne -lt -le -gt -ge string = != < <= > >=

Heres an example of warning the user the 2 command line args are needed: if [ $# -ne 2 ]; then echo Usage: thisscript arg1 arg2 exit fi

There are many other options that are very useful in conditions. Here are some: -nt -z -o -a -e -f -d -s newer than zero or and exists file directory size the first arguments the argument following is null (zero) the file or directory exists file exists directory exists, or file is a directory file exists and size is greater than 0

You can also put ! in front, such as if [ ! f somefile.txt ]; then The brackets are actually command names! That is [ is a synonym for the Unix command test. So the following is how bash really sees the above if test ! f somefile.txt then 3. Variables Bash has variables and arrays. They are dynamically typed, which means they take the type of the object they current contain. Setting a variable is simple: X=5 Accessing the variables value is a little strange: you have to put a $ in front of it: echo $X Variables can be concatenated into other things, even inside strings, without special operators. This is a feature that makes scripting languages so fast: X=.java ls /user/home/alvin/*$X echo We are inspecting all of alvins $X files Integer variables are set by simply assigning numbers to them. But afterwards the numerical value of the variable has to be accessed inside double parentheses: y=0 y=$((y+1))

To get data from the user and store it in a variable, use the read command. Typically you will want to prompt the user first. Normally the computer does not skip to the next line after prompting, which is what the n option does below: echo n "Enter your age: " read age echo "You said you were $age years old" 4. For loops Most bash shell programmers do not need the full power of a general purpose programming language, so they tend not to need while loops, but for loops are quite often used to iterate over a collection. The most obvious use is to iterate over a list of files. We use the for in loop for this: for i in *.java do wc $i done The generator that follows the keyword in is usually an expression that generates filenames using a wildcard. The variable (i in this example) successively takes on the values from the generator, which can then be used inside the loops body as shown. This gets the word count of each Java file (wc is the Unix word count command). If you want to generate a numerical sequence, use the seq command. The syntax is seq starting-value increment ending-value $ seq 1 1 10 1 2 10 for i in seq 1 10 100 do cat $i done Newer versions of bash have a more concise syntax. You can find the version by doing $ bash version If you want to go up by 2s instead of 1s, use seq 1 2 10.

If you need only some values you can simply specify them. They don't even need to be in order. for i in 4 2 8 9 7 6 1 5 do cat file$i done 5. Regular expressions The bash shell permits wildcards that include some of the standard regular expression characters. You typically only need a few of these. They do differ slightly from REs in Java or other languages. * ? [a-z] [0-9] 0 or more characters 0 or 1 character range of characters that are lower case letters range of digits

The difference has to do with the fact that you do not apply * or ? to a preceding character as you do in Java. That is, * all by itself means 0 or more characters. You often see this in Unix commands: $ ls *.java $ rm huge?? $ wc file[0-9].txt 6. Miscellaneous The backquote substitution is useful because it runs a command and inserts the standard output of that command directly into the bash statement, as if it were a string: if [ `whoami` != 'root' ]; then echo "You must be root to run this script" exit fi Here's how to see if the last line of the file message.txt contains "stupid": if [ `tail -1 message.txt` = "stupid" ]; then echo "This is indeed stupid!" exit fi List all the Java files remove all files like huge03, hugeab, etc. word count of file0.txt, file1.txt, etc. up to file9.txt

The here document is another form of indirect redirection. It allows you to embed data inside a shell script without explicitly creating the file. You can even put $variables in it and bash will substitute the variables' values. The start of the here document begins with << and a string of your choice. The last line is the same string, but it must be at the beginning of the line and contain no extraneous characters: wc <<END Mary had a little lamb Its fleece was white as snow and everywhere that Mary went the lamb was sure go. END To debug your shell scripts, there are some options. To just check the syntax of your script without running, use n: $ bash n somescript To run in verbose mode, use v. To show the substitutions in each script line, use x. $ bash vx somescript You can call other bash shell scripts. As long as there is a file with the right name, just call it as you would from the command line. These can even be recursive! Suppose you were using a very old Unix whose grep did not have the r option to recurse. Here's a shell script: supergrep searchstring=$1 for f in $2/* do if [ -d $f ]; then # $f is a directory (cd $f; supergrep $i $searchstring ) # go into that directory and search else # $f is a regular file grep $searchstring $f fi done Here's how you would call it: $ supergrep stupid SOMEDIR You may get path errors unless you do one of two things: put the directory that contains the supergerp file into your path, or you specify an absolute address. That is, in the supergrep script, specify the full path such as /home/users/meyer/supergrep.

Unfortunately, you can't do the following, which means to search every file in the current directory because the * will expand to every filename in the current directory. $ supergrep stupid * You could possibly refer to all the command line arguments by $* but the first argument, which is a string to find, will be counted, too. There is a handy shift command to shift all the command line arguments "to the left" by 1, and get rid of the first one. Here's the shell of what you'd have to do: searchstring=$1 echo "searchstring=$searchstring" shift for i in $* do echo -n $i " " done 7. Saving your keystrokes Every command that you type is saved. You can retrieve them with the history command $ history You could save these by redirecting history's output to a file. This is a cheap and easy way to creating the beginning of a shell script. You can also capture all the commands as well as the output of a session by typing $ script This creates a shell whose output is tee'd to a file named typescript. When you press Control-D to end the shell, this file is closed and available for editing. You might want to rename it since the next script command will truncate it. $ mv typescript "Tuesday's script" One caveat is that you should not use a full-screen editor when you are in this script-capture mode because the codes that form the on-screen pictures get put into the typescript file!

8. More to Learn Go to google.com and type in "bash shell scripting" for some good references. Another way to learn is to go to the bash shell directory and look at the man pages for bash and test. $ man bash $ man test $ info bash $ info test

Вам также может понравиться