December 19th, 2007
# for I in `echo $*` do for J in 15 2 1 9 do kill -$J $I && sleep 1 done done exit 0 This script cycles through a list of process IDs specified on the command line. To ensure that the process has been terminated, several signals are sent to the process in increasing levels of severity. The first signal attempted is 15 (signal number 15 is SIGTERM), which requests the termination of the process. The next signal is 2 (signal 2 is SIGINT), representing an attempted interrupt from the keyboard (i.e., a Ctrl+C sequence or similar action). Signal 1, SIGHUP, is then tried, which attempts to kill the process by indicating that the controlling terminal has “hung up,” terminology left over from when serial consoles were more prevalent. Finally, signal 9, SIGKILL, is sent to the process. This last resort signal doesn t allow the process to perform any activities on exiting it just tries to “kill with impunity.” A one-second delay, induced only if previous attempts to kill the process have failed, gives the process some time to trap each signal and exit properly. For a complete list of signals, refer to the signal 7 manual page (type man 7 signal). More advanced scripts are examined throughout the course of this chapter. System Initialization In the boot process, the transfer from the kernel phase (the loading of the kernel, probing for devices, and loading drivers) to init is indicated by the following lines: INIT: version 2.78 booting Welcome to Red Hat Linux The init program, part of the SysVinit RPM package, is now in control. Known as the father of all processes, the output from ps always lists init as PID (process identifier) 1. Its actions are directed by the /etc/inittab file, which is reproduced next. The inittab file The following text shows the contents of the /etc/inittab file as it is delivered with Red Hat Linux: # # inittab This file describes how the INIT process should set up # the system in a certain run level. # # Author: Miquel van Smoorenburg, # Modified for RHS Linux by Marc Ewing and Donnie Barnes # # Default runlevel. The runlevels used by RHS are: # 0 - halt (Do NOT set initdefault to this) # 1 - Single user mode # 2 - Multiuser, without NFS (The same as 3, if you do not have networking) # 3 - Full multiuser mode # 4 - unused # 5 - X11 # 6 - reboot (Do NOT set initdefault to this)
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.
Posted in Smart | No Comments »
December 19th, 2007
du -s $I > $TMPfile done sort -rn $TMPfile rm $TMPfile exit 0 In this script, awk chooses particular bits of information from the /etc/passwd file. Using the colon as a field separator (the -F: option), awk checks whether the third field on each line (the user ID, or UID) is greater than or equal to 500 (by default, the starting point for regular user accounts). If so, that user s home directory (the sixth field) is returned. The for loop cycles through the list returned by awk, and performs a disk usage check on each directory. The results are stored in a unique temporary file (the $$ variable represents the process ID of the running program). The temporary file is numerically sorted and then removed. The results from either of the preceding programs may look like: 936890 /home/jsmith 489349 /home/oracle 20439 /home/wilhelm 748 /home/acorad 8 /home/gandalf 8 /home/johnson 8 /home/cseitz 8 /home/buchanan Cross-Reference The awk command is used to scan a file for particular patterns, based on rules that you provide. It can then output that information in a form that you choose. A script for checking scripts Occasionally, when testing scripts, it s helpful to take a look at what the script has accomplished so far. When called from another shell script, the following script suspends the running program and lets you (via another Terminal window or virtual terminal) look for expected temporary files or altered conditions. This can indicate whether a program is performing as expected, or if it needs a little more work. #!/bin/bash # Count=1 while : do echo -n “$Count Continue? (y/n): ” read ANS case “$ANS” in y|Y) break ;; esac let Count+=1 done exit 0 The colon (:) on the fourth line does absolutely nothing. It functions only as a placeholder, and allows the while loop to repeat until a y or Y is entered (causing the break to exit the loop). The Count variable keeps track of the number of times the loop has run. The -n option to echo suppresses printing the new line and positions the cursor just beyond the Continue? (y/n): prompt to wait for input. A script to kill processes Another example that may be used frequently is the following script to kill processes nicely. This script gives the processes every opportunity to clean up any temporary files, notify the parent process that it is exiting, and terminate quietly. #!/bin/bash
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.
Posted in Smart | No Comments »
December 18th, 2007
then mkdir $DIR cp /home/grd/proj/template $DIR/file_def fi let Count+=1 done The preceding loop creates a directory, if the directory doesn t already exist, and copies a template file to it. This repeats until the value of the COUNT variable is equal to 34 (requiring 33 iterations). Trying some simple shell scripts Sometimes the simplest of scripts can be the most useful. If you type the same sequence of commands repetitively, it makes sense to store those commands (once!) in a file. Here are some examples of simple, but useful, shell scripts. A simple backup script If you ve been collecting data for a research project for the past two years, you ll want to keep backup copies of your work in case something should happen to the original files. Rather than type out the full command each time you d like to make a backup, simply store the commands in a shell script: #!/bin/bash # mt /dev/rft0 rew cd /home/rp008a/data tar cvf /dev/rft0 mt /dev/rft0 rewoffl exit 0 This script runs the mt command with the rew option to rewind the tape in the tape drive, attached to the floppy controller (/dev/rft0). Next, the cd command changes the current directory to /home/rp008a/data. The tar command creates the archive (c) from files in the current directory, verbosely (v) describes what it is doing, and outputs the archive file to the tape device (f /dev/rft0). Then the mt command rewinds and ejects the tape (rewoffl) from the tape device (/dev/rft0). For further automation, see the section on the cron facility later in this chapter. Cross-Reference It is just as important to back up the operating system. See Chapter 13 for details on backing up and restoring files. Scripts to check disk space Another common administrative issue is disk space, a resource that always seems to be in short supply. If you find yourself regularly checking the size of users home directories, the following script may be handy: #!/bin/bash # cd /home ; du -s * | sort -rn Cross-Reference Use the -h option with du to make the output of du friendlier. This script looks at all directories in /home and reports on their size in kilobytes. The output is sorted numerically, with the largest directory at the top of the list. If you have users with home directories other than the /home directory, the following (slightly more complex) script is more useful: #!/bin/bash # TMPfile=/tmp/sh$$tmp for I in `awk -F: { if ($3 >= 500) print $6 } /etc/passwd` do
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.
Posted in Smart | No Comments »
December 18th, 2007
;; *) { body } ;; esac An example of the case command follows. This fragment of code sets the TYPE and RCFILE variables based on the user s default shell as reported in the seventh (colon-separated) field of the /etc/passwd file: Shell=`grep “^$USER:” /etc/passwd | awk -F: { print $7 } ` case “$Shell” in /bin/sh) TYPE=Bourne RCFILE=”.profile” ;; /bin/csh) TYPE=C RCFILE=”.cshrc” ;; /bin/bash) TYPE=Bourne RCFILE=”.bashrc” ;; /bin/tcsh) TYPE=C RCFILE=”.tcshrc” ;; *) TYPE=other RCFILE=”unknown” ;; esac The asterisk (*) is used as a catchall. If none of the other entries are matched on the way down the loop, the asterisk is matched and the value is set to unknown. The while . . . do and until . . . do loops Two other possible looping constructs are the while . . . do loop and the until . . . do loop. The structure of each is presented here: while condition until condition do do { body } { body } done done In a while loop, the condition is usually a test statement, but it can also be used to read input until an End-of-File () is encountered. If a test condition is used, the body of the loop is executed until the condition evaluates to false (a return code of 1). A sample is included here: while read COL1 COL2 COL3 COL4 do echo -n ” | X $COL2 | $COL3 ” > /home/ben/DB echo “| $COL4 | $COL1 X |” > /home/ben/DB done This loop reads values (in groups of four) from the keyboard, rearranges the column order, and outputs them to a file in a particular format. The until loop executes the code in the body until the test evaluates to true (a return code of 0). At that point, the loop exits. COUNT=1 until [ $Count -eq 34 ] do DIR=/home/grd/proj/$Count if [ ! -d $DIR ]
In case you need quality webspace to host and run your web applications, try our personal web hosting services.
Posted in Smart | No Comments »
December 17th, 2007
-G file Does the file exist and is its group ownership the same as the current user s primary group? -k file Does the file have the sticky bit set? -L file Is the file a symbolic link? -n string Is the length of the string greater than 0 bytes? -O file Does the file exist and does the current user own it? -p file Is the file a named pipe? -r file Does the file exist, and is it readable? -s file Does the file exist, and is it larger than 0 bytes? -S file Does the file exist, and is it a socket? -t fd Is the file descriptor open? -u file Does the file have the set-user-id bit set? -w file Does the file exist, and is it writable? -x file Does the file exist, and is it executable? -z string Is the length of the string 0 bytes? expr1 -a expr2 Are both the first expression and the second expression true? expr1 -o expr2 Is either of the two expressions true? file1 -nt file2 Is the first file newer than the second file (using the modification timestamp)? file1 -ot file2 Is the first file older than the second file (using the modification timestamp)? file1 -ef file2 Are the two files associated by a link (a hard link or a symbolic link)? var1 -eq var2 Is the first variable equal to the second variable? var1 -ge var2 Is the first variable greater than or equal to the second variable? var1 -gt var2 Is the first variable greater than the second variable? var1 -le var2 Is the first variable less than or equal to the second variable? var1 -lt var2 Is the first variable less than the second variable? var1 -ne var2 Is the first variable not equal to the second variable? When the expression is evaluated, the result is either a 0 (indicating “true”) or a 1 (indicating “false”). Here are some examples that demonstrate the uses of the if statement and a test expression: if [ -x /sbin/ifconfig ] if [ $4 -eq “nl” ] if [ $# -gt 2 ] if [ -z $HOSTNAME ] In the previous example, the first statement checks if the /sbin/ifconfig program is executable. The second example checks if the string value nl is equal to the value stored in $4 (the fourth command-line argument). The next line checks if the number of command-line arguments (represented by the $# variable) is greater than two. The last example determines if the variable $HOSTNAME is empty. The case command for nested if statements Another frequently used construct is the case command. Similar to a switch statement in programming languages, this can take the place of several nested if statements. A general form of the case statement is as follows: case “VAR” in Result1) { body } ;; Result2) { body }
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.
Posted in Smart | No Comments »
December 17th, 2007
Each element in the loop is separated from the next by white space. For that reason, you should be careful if you are directing output of a command to use as your LIST. As soon as the for loop sees a space or a tab, it runs the loop on it. For example, if you direct the output of the ls command to the loop, the loop evaluates each filename separately. However, if you use the output of ls -l, the loop also evaluates every other piece of information in the list (such as file owner, permission bits, and so on) something that you probably don t want to do. The if . . . then test loop Another common loop is constructed by testing variables within an if statement. The possible variations of an if . . . then test loop are shown here: if [ expression ] then { body } fi if [ expression ] then { body } else { body } fi if [ expression ] then { body } elif [ expression ] then { body } else { body } fi In this type of loop, each of the expressions is tested. Based on the results of that test, one of the actions that follow is taken. Table 12-3 lists the possible test expressions that can exist between the brackets in an if statement. The left bracket itself begins the “test” part of the statement. In fact, each of the preceding if statements can be rewritten without brackets as in: if test expression Table 12-3: Operators for Test Expressions Operator What Is Being Tested? -b file Is the file block special (e.g., a block device)? Used to identify disk and tape devices. -c file Is the file character special (e.g., a character device)? Used to identify serial lines and terminal devices. -d file Is the file a directory? -e file Does the file exist? -f file Does the file exist, and is it a regular file (e.g., not a directory, socket, pipe, link, or device file)? -g file Does the file have the set-group-id bit set?
You want to have a cheap webhost for your apache application, then check apache web hosting services.
Posted in Smart | No Comments »
December 15th, 2007
= = != equality and inequality & bitwise AND ^ bitwise XOR (exclusive OR) | bitwise OR && logical AND || logical OR = *= /= %= += -= <<= >= &= ^= |= assignment Table 12-2: Mathematical Operations in expr Operator Description * / % multiplication, division, and modulus (remainder) + - addition and subtraction < <= >= > != = = = Comparison: less than; less than or equal to; greater than or equal to; greater than; not equal to; and two representations of equal to & logical AND | logical OR -eq equal to -ne not equal to -lt less than -le less than or equal to -gt greater than -ge greater than or equal to | logical OR Using programming constructs in shell scripts One of the features that make shell scripts so powerful is their implementation of looping constructs similar to those found in compiled programming languages. You can use several different types of loops, depending on your needs. The for . . . do loop One of the most commonly used loops is the for . . . do loop. It iterates through a list of values, executing the body of the loop for each element in the list. The syntax and examples are presented here: for VAR in LIST do { body } done In the preceding example, the for loop assigns the values in LIST to VAR one at a time. Then for each value, the body in braces between do and done are executed. VAR can be specified by any valid variable name. LIST can be composed of any values that can be defined (numbers, letters, path names, dates, etc.) because each item in the list is treated as a string value in the body of the loop. Any commands can appear in the body. The beginnings of some possible loops are shown here: for SECTION in 1 2 3 4 5 6 7 8 for DIRS in /home /etc /usr /var for DISK in /dev/hda /dev/hdb /dev/sda for PARTITION in a b d e
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.
Posted in Smart | No Comments »
December 15th, 2007
Variables can contain the output of a command. The advantage of having a variable set to the output of a command is that you can take advantage of information that changes in certain conditions. In the following example, the MACHINE variable is set to the output of the uname -n command. This always sets MACHINE to the name of your current computer, as follows: MACHINE=`uname -n` The command contained within the back quotes is executed in a subshell, and the output is stored in the variable name. In this case, the uname -n command outputs the computer’s hostname (such as baskets.handsonhistory.com) and assigns that value to the MACHINE variable. Note A subshell provides a way to execute a command, or series of commands, outside of the current shell. The subshell is similar to the current shell in that it remembers locations of commands and values of environment variables from the parent shell. However, changes to the subshell’s environment are not automatically passed back to the parent shell. Variables can also take on the values of other variables. This is a way of taking advantage of changing information as the shell script runs. For example, a shell script could determine an account balance ($CurrentBalance) and then store that value in the BALANCE variable, enabling the value to be saved as follows: BALANCE=$CurrentBalance Note When being assigned, only the variable name is necessary. When being referenced, the variable name must be prefaced by a dollar sign ($). Performing arithmetic evaluation in shell scripts While variables in shell scripts can contain numbers, all values are treated as alphanumeric strings unless otherwise instructed by the built-in typeset command. Integer arithmetic can be performed using the built-in let command or through the external expr command. For example, given that the variable BIGNUM contains the value 1024, the following two commands would both store the value 64 in the RESULT variable: let Result=$BIGNUM/16 Result=`expr $BIGNUM / 16` Note While most elements of shell scripts are relatively free form (where white space, such as spaces or tabs, is insignificant), both of the previous commands are particular about spacing. The let command insists on no spaces between each operand and the mathematical operator, whereas the syntax of the expr command requires white space between each operand and its operator. Valid mathematical operations available in bash s built-in let command are listed in Table 12-1 in order of decreasing precedence. Multiple operators in the same row indicate equal precedence. Table 12-2 similarly lists the valid mathematical operators for the expr command. Table 12-1: Mathematical Operations in let Operator Description + - unary plus and minus ! ~ logical and bitwise negation * / % multiplication, division, and modulus (remainder) + - addition and subtraction << > left and right bitwise shift < <= >= > less than; less than or equal to; greater than or equal to; and greater than comparisons
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.
Posted in Smart | No Comments »
December 15th, 2007
The filename is used as an argument to the shell (e.g., bash script_file). In this method, the file does not need to be executable; it just contains a list of shell commands. The shell specified on the command line is used to interpret the commands in the script file. This is most common for quick, simple tasks. The shell script is executed by specifying the name of the file on the command line. This requires that the first line of the shell script contain the name of the shell interpreter that is to be used (e.g., #!/bin/bash as the first line of the file) and that the execute bit is set. This method is most common for complex scripts that may be used frequently. The first line of a shell script is the only line where the pound sign (#) isn’t interpreted as a comment. Cross-Reference See Chapter 3 for information on chmod and read/write/execute file permissions. The examples in this chapter are of the second variety. When scripts are executed in either manner, options to the program may be specified on the command line. Anything following the name of the script is referred to as a command-line argument. These are referenced within the script as the variables $1, $2, $3, . . . $n. The name of the script itself is held within the variable $0. Note that these are positional parameters, meaning that they refer to a position of information on the command line. While it is recommended that you choose meaningful variable names, there s still no substitute for active commenting throughout the design of the shell script. The pound sign (#) prefaces comments and can take up an entire line or exist on the same line as script code. When you are writing more complex shell scripts, it is best to implement them in stages, making sure the logic is sound at each step before continuing. One way to make sure things are working as expected during testing is to place an echo statement at the beginning of lines within the body of a loop. That way, rather than executing the code, you can see what will be executed without making any permanent changes. Another way to accomplish the same goal is to place dummy echo statements at various places throughout the code. If these lines get printed, you know the correct logic branch is being taken. With the bash shell, you could also use set +x near the beginning of the script to display each command that is executed. Besides commands, shell scripts can contain such components as user-defined variables, program constructs (such as loops and conditionals), and arithmetic instructions. These topics are described in the following sections. Creating user-defined variables in shell scripts Often within a shell script, you want to reuse certain items of information. During the course of processing the shell script, the name or number representing this information may change. To store information used by a shell script in a way that it can be easily reused, you can set variables. Variable names within shell scripts are case-sensitive and can be defined in the following manner: NAME=value The first part of a variable is the variable name, and the second part is the value set for that name. For example, you can define a variable containing the city in which you live as follows: City=”Springfield” Technically, quoting is only necessary to preserve spacing within values, but it may aid in readability. Double quotes (”) are considered weak quotes, while single quotes (’) are considered strong quotes. Any special characters contained in a string surrounded by single quotes (for example, ’string’) are disabled. With double quotes, however, all special characters are disabled except dollar sign ($), single quote (’), and backslash ().
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.
Posted in Smart | No Comments »
December 14th, 2007
Chapter 12: Automating System Tasks Overview You d never get any work done if you had to type every command that needs to be run on your Red Hat Linux system when it starts up. Likewise, you could work more efficiently if you grouped together sets of commands that you run all the time. Shell scripts can handle these tasks. A shell script is a group of commands, functions, variables, or just about anything else you can use from a shell. These items are typed into a plain-text file. Then that file can be run as a command. Red Hat Linux uses system initialization shell scripts during system start-up to run commands needed to get things going. You can create your own shell scripts to automate the tasks you need to do regularly. This chapter provides a rudimentary overview of the inner workings of shell scripts and how they can be used. You learn how shell scripts are responsible for the messages that scroll by on the system console during booting and how simple scripts can be harnessed to a scheduling facility (such as cron or at) to simplify administrative tasks. You also learn to fine-tune your machine to start at the most appropriate run level and to only run the daemons that you need. With that understanding, you ll be able to personalize your environment and cut down on the amount of time you spend repetitively typing the same commands. Understanding Shell Scripts A shell script is a plain-text file containing a sequence of commands. It can be a simple one-line command that you d prefer not to type repetitively; a complex program containing several loops, conditional statements, mathematical operations, and control structures; or anything in between. Shell scripts are equivalent to batch files in DOS/Windows but offer greater flexibility and control through advanced looping constructs, logical operators, functions, and a larger base of commands to use. Shell scripts have much the same syntax as programming languages and are capable of handling many of the same tasks. Nearly a dozen different shells are available in Red Hat Linux, some of which function virtually identically in an interactive environment. From a programming standpoint, there are basically two varieties, those based on the Bourne shell (sh), and those derived from the C shell (csh). All code and examples in this chapter are based on the bash (Bourne-again shell) environment, which implements a superset of the original Bourne shell. In fact, /bin/sh is a symbolic link to /bin/bash. The syntax (that is, the way commands and options are constructed) of the C shell is similar to that of the C programming language. It has interactive capabilities that are not included in most Bourne shells. Each shell also uses different configuration files and different methods of setting shell environment variables. Executing shell scripts Shell scripts are files of text commands, functions, environment variables, and/or comments that you can run as commands. In theory, a shell script is a way of grouping a sequence of commands instead of typing them at a shell prompt. In reality, shell scripts can be as complex as any executable program. An advantage of shell scripts is that they can be opened in any text editor to see what it does. A disadvantage is that shell scripts often execute more slowly than compiled programs. There are two ways to execute a shell script:
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.
Posted in Smart | No Comments »