Showing posts with label General. Show all posts
Showing posts with label General. Show all posts

Thursday, 22 March 2012

How to turn old hard drives into a secure file server: Tutorial | Techgig


Over the last year or two we've been taking advantage of the incredible price drop in traditional spinning hard drives. Until the tragic floods in Thailand, prices had dropped as low as £40 per terabyte.
This had led to many of us upgrading our existing systems with new drives - leaving small piles of 160GB to 500GB drives littered around the country like digital cairns.
The obvious question that springs from this is: what to do with these drives? It's unlikely you'll just want to throw them away; it's a waste of a good drive and even less likely if it had personal data on it. Besides using it in a spare PC you're building, the solution we've struck on is to use them at the heart of a storage pool server.  For more details, click the following link.

Tech News - How to turn old hard drives into a secure file server: Tutorial | Techgig

Monday, 8 August 2011

How to create a simple shell script

Shell scripts are short programs that are written in a shell programming language and interpreted by a shell process. A shell is a program that provides the traditional, text-only user interface for Unix-like operating systems. Its primary function is to read commands that are typed into a console or terminal window and then execute (i.e., run) them. The default shell on Linux is the very commonly used and highly versatile bash. 
A feature of bash and other shells used on Unix-like operating systems is that each contains a built-in programming language, referred to as a shell programming language or shell scripting language, which is used to create shell scripts. 
A First Script
The following example provides a useful introduction to creating and using shell scripts. The script clears the monitor screen of all previous lines and then writes the text Good morning, world. on it.
For that open a text editor such as gedit or vi, and type the following three lines exactly as shown on a new, blank page:
#!/bin/bash
clear
echo "Good morning, world."
 
After saving this plain text file, with a file name such as morning or anything else desired, the script is complete and almost ready to run. Scripts are typically run by typing a dot, a forward slash and the file name (with no spaces in between) and then pressing the ENTER key. Thus, for example, if the above script were saved with the name morning, an attempt could be made to execute it by issuing the following command:
./morning
However, the script probably will not run, in which case an error message will appear on the screen such as bash: ./morning: Permission denied. This is because the permissions for the file first have to be set to executable. The problem can easily be solved by using the chmod command with its 755 option (which will allow the file creator to read, write and execute the file) while in the same directory as that in which the file is located as follows:
chmod 755 morning
Now the script is ready to run by typing the following, again while in the same directory, and then pressing the ENTER key:
./morning
Now it display a message on the screen
Good morning, world.
At the same time the script clears all previous lines from the screen.
How it works?
The first of the three lines tells the operating system what shell to use to interpret the script and the location of the shell. The shell is bash, which is located in the /bin directory. Thus the line contains /bin/bash. This instruction is always preceded by a pound sign and an exclamation mark in order to inform the operating system that it is providing the name and location of the shell.
The second line tells the shell to issue the clear command. This is a very simple command that removes all previous commands and output from the console or terminal window in which the command was issued. 
The third line tells the shell to write the phrase Good morning, world. on the screen. It uses the echo command, which instructs the shell to repeat whatever follows it. The quotation marks are not necessary in this case.

Sunday, 7 August 2011

Make - UNIX Utility

In this post I want to discuss about UNIX make Utility. Make is one of the most widespread, primarily due to its inclusion in Unix, starting with the PWB/UNIX 1.0, which featured a variety of tools targeting software development tasks. It was originally created by Stuart Feldman in 1977 at Bell Labs.

The purpose of the make utility is to determine automatically which pieces of a large program need to be recompiled, and issue the commands to recompile them. You can use make with any programming language whose compiler can be run with a shell command.

To prepare to use make, you must write a file called the makefile that describes the relationships among files in your program, and the states the commands for updating each file. In a program, typically the executable file is updated from object files, which are in turn made by compiling source files.

Once a suitable makefile exists, each time you change some source files, this simple shell command: make suffices to perform all necessary recompilations. The make program uses the makefile data base and the last-modification time of the files to decide which of the files need to be updated. For each of those files, it issues the commands recorded in the data base.
Syntax:

make [ -f makefile ] [option] ... target ...

Make executes commands in the makefile to update one or more target names, where names is typically a program. If no -f option is present, make will look for the makefiles GNUmakefile, makefile, and Makefile, in that order.

Makefile structure
A makefile consists of dependency lines of text which define a target (a rule) followed by a colon and optionally a set of files on which the target depends. The dependency line is arranged so that the target (left hand of : character) depends on components (right hand of : character).

After each dependency line, a series of lines of tab-indented text may follow which define how to transform the components (usually source files) into the target (usually the "output"). If any of the components have been modified, the command below are run. The basic structure is,

# Comments are started with the hash(#) symbol.
target [target ...]: [component ...]
[<TAB>command 1]
.
.
.
[<TAB>command n]
Descripter files
To operate make needs to know the relationship between your program's component files and the commands to update each file. This information is contained in a descriptor file you must write calledMakefile or makefile.
Comments
Comments can be entered in the descriptor file following a pound sign ( # ) and the remainder of the line will be ignored by make. If multiple lines are needed each line must begin with the pound sign.
# This is a comment line
Dependency rules
A rule consist of three parts, one or more targets, zero or more dependencies, and zero or more commands in the following form:

target1 [target2 ...] :[:] [dependency1 ...] [; commands]
[<tab> command]

Note: each command line must begin with a tab as the first character on the line and only command lines may begin with a tab.
Target
A target is usually the name of the file that make creates, often an object file or executable program.
Macros
Macros allow you to define constants. By using macros you can avoid repeating text entries and make descriptor files easier to modify. Macro definitions have the form
NAME1 = text string
NAME2 = another string

Simple Example

This is an example descriptor file to build an executable file called prog1. It requires the source files file1.cc, file2.cc, and file3.cc. An include file, mydefs.h, is required by files file1.cc andfile2.cc. If you wanted to compile this file from the command line using C++ the command would be
Note:In this example  prefixed with a percent character ( % ) it is a UNIX C-shell command line.
    % CC -o prog1 file1.cc file2.cc file3.cc
A descriptor file could run the same command better by using the simple command
    % make prog1
or if prog1 is the first target defined in the descriptor file

     % make

This example descriptor file is much longer than necessary but is useful for describing what is going on.

prog1 : file1.o file2.o file3.o
CC -o prog1 file1.o file2.o file3.o

file1.o : file1.cc mydefs.h
CC -c file1.cc

file2.o : file2.cc mydefs.h
CC -c file2.cc

file3.o : file3.cc
CC -c file3.cc

clean :
rm file1.o file2.o file3.o

Let's go through the example to see what make does by executing with the command make prog1 and assuming the program has never been compiled.
  1. make finds the target prog1 and sees that it depends on the object files file1.o file2.o file3.o
  2. make next looks to see if any of the three object files are listed as targets. They are so make looks at each target to see what it depends on. make sees that file1.o depends on the files file1.cc andmydefs.h.
  3. Now make looks to see if either of these files are listed as targets and since they aren't it executes the commands given in file1.o's rule and compiles file1.cc to get the object file.
  4. make looks at the targets file2.o and file3.o and compiles these object files in a similar fashion.
  5. make now has all the object files required to make prog1 and does so by executing the commands in its rule.


Saturday, 6 August 2011

Sed - UNIX Tool

In this post I want to discuss about sed (Stream editor). Sed is a Unix utility that parses text and implements a programming language which can apply transformations to such text. It was developed by Lee E. McMohan of Bell Labs at 1974. It is available today for most operating systems.

Sed has several commands, the most essential command of sed is the substitution command: s. The substitution command changes all occurrences of the regular expression into a new value.

A simple example is changing “day” in the “old” file to “night” in the “new” file.

sed 's/day/night/' <old > new

I must emphasize the sed editor changes exactly what you tell it to. So if you executed

echo Sunday | sed 's/day/night/'

This would output the word “Sunnight” because sed found the string “day” in the input.
There are four parts to this substitute command:

s                 Substitute command
/../../        Delimeter
day           Regular expression pattern search pattern
night         Replacement string

The slash as a delimeter

The character after the s is the delimiter. It can be anything you want, however. If you want to change a pathname that contains a slash - say /usr/local/bin to /common/bin – you could use the backslash to quote the slash:

sed 's/\/usr\/local\/bin/\/common\/bin/' <old >new

we can also use an underline, colons or “|”  character instead of a slash as a delimiter:

sed 's_/usr/local/bin_/common/bin_' <old >new
sed 's:/usr/local/bin:/common/bin:' <old >new
sed 's|/usr/local/bin|/common/bin|' <old >new
        
Using & as the matched string

$ used for pattern matching. It is easy to do this if you are looking for a particular string:

sed 's/abc/(abc)/' <old >new

This won't work if you don't know exactly what you will find. The solution requires the special character "&." It corresponds to the pattern found.

sed 's/[a-z]*/(&)/' <old >new

You can have any number of "&" in the replacement string. e.g. the first number of a line:

% echo "123 abc" | sed 's/[0-9]*/& &/'
123 123 abc

If the input was "abc 123" the output would be unchanged.

% echo "123 abc" | sed 's/[0-9][0-9]*/& &/'
123 123 abc

The original sed did not support the "+" metacharacter. GNU sed does. It means "one or more matches". So the above could also be written using
% echo "123 abc" | sed 's/[0-9]+/& &/'
123 123 abc

Using \1 to keep part of the pattern

The "\1" is the first remembered pattern, and the "\2" is the second remembered pattern. Sed has up to nine remembered patterns. If you wanted to keep the first word of a line, and delete the rest of the line, mark the important part with the parenthesis:

sed 's/\([a-z]*\).*/\1/'

"[a-z]*" matches zero or more lower case letters, Therefore if you type

echo abcd123 | sed 's/\([a-z]*\).*/\1/'

This will output "abcd" and delete the numbers.
If you want to switch two words around, you can remember two patterns and change the order around:

sed 's/\([a-z]*\) \([a-z]*\)/\2 \1/'

You may want to insist that words have at least one letter by using

sed 's/\([a-z][a-z]*\) \([a-z][a-z]*\)/\2 \1/'

If you want to eliminate duplicated words, you can try:

sed 's/\([a-z]*\) \1/\1/'

If you want to detect duplicated words, you can use

sed -n '/\([a-z][a-z]*\) \1/p'

If you wanted to reverse the first three characters on a line, you can use

sed 's/^\(.\)\(.\)\(.\)/\3\2\1/'

/g -Global replacement

let's place parentheses around words on a line. Instead of using a pattern like "[A-Za-z]*" which won't match words like "won't," we will use a pattern, "[^ ]*," that matches everything except a space. The following will put parenthesis around the first word:

sed 's/[^ ]*/(&)/' <old >new

If you want it to make changes for every word, add a "g" after the last delimiter and use the work-around:

sed 's/[^ ][^ ]*/(&)/g' <old >new

/1, /2, etc. Specifying which occurance

If you want to modify a particular pattern that is not the first one on the line, you could use "\(" and "\)" to mark each pattern, and use "\1" to put the first pattern back unchanged. This next example keeps the first word on the line but deletes the second:

sed 's/\([a-zA-Z]*\) \([a-zA-Z]*\) /\1 /' <old >new

There is an easier way to do this. You can add a number after the substitution command to indicate you only want to match that particular pattern. Example:

sed 's/[a-zA-Z]* //2' <old >new

You can combine a number with the g (global) flag. For instance, if you want to leave the first world alone , but change the second, third, etc. to DELETED, use /2g:

sed 's/[a-zA-Z]* /DELETED /2g' <old >new

/p – print
If you use an optional argument to sed, "sed -n," it will not, by default, print any new lines. When the "-n" option is used, the "p" flag will cause the modified line to be printed.

sed -n 's/pattern/&/p' <file

Write to a file with /w filename

you can specify a file that will receive the modified data. An example is the following, which will write all lines that start with an even number, followed by a space, to the file even:

sed -n 's/^[0-9]*[02468] /&/w even' <file

previously, I have only used one substitute command. If you need to make two changes, and you didn't want to read the manual, you could pipe together multiple sed commands:

sed 's/BEGIN/begin/' <old | sed 's/END/end/' >new

Multiple commands with -e command

One method of combining multiple commands is to use a -e before each command:

sed -e 's/a/A/' -e 's/b/B/' <old >new

sed -f scriptname

If you have a large number of sed commands, you can put them into a file and use

sed -f sedscript <old >new

where sedscript could look like this:

# sed comment - This script changes lower case vowels to upper case
s/a/A/g
s/e/E/g
s/i/I/g
s/o/O/g
s/u/U/g

sed in shell script
If you have many commands and they won't fit neatly on one line, you can break up the line using a backslash:

sed -e 's/a/A/g' \
-e 's/e/E/g' \
-e 's/i/I/g' \
-e 's/o/O/g' \
-e 's/u/U/g' <old >new


How to Run AWK Programs?

In my previous post I Explained about the AWK, In this post we have to check How to run AWK programs.
The basic function of awk is to search files for lines (or other units of text) that contain certain patterns. When a line matches one of the patterns, awk performs specified actions on that line. awk keeps processing input lines in this way until it reaches the end of the input files. An awk program looks like this:

pattern { action }
     pattern { action }
     ...
There are several ways to run an awk program. If the program is short, it is easiest to include it in the command that runs awk, like this:
awk 'program' input-file1 input-file2 ...
When the program is long, it is usually more convenient to put it in a file and run it with a command like this:
awk -f program-file input-file1 input-file2 ...
Once you are familiar with awk, you will often type in simple programs the moment you want to use them. Then you can write the program as the first argument of the awk command, like this:
     awk 'program' input-file1 input-file2 ...
where program consists of a series of patterns and actions, as described earlier.
This command format instructs the shell, or command interpreter, to start awk and use the program to process records in the input file(s).

There are single quotes around program so the shell won't interpret any awk characters as special shell characters. The quotes also cause the shell to treat all of program as a single argument for awk, and allow program to be more than one line long.

This format is also useful for running short or medium-sized awk programs from shell scripts, because it avoids the need for a separate file for the awk program.

Running awk Without Input Files
You can also run awk without any input files. If you type the following command line:
awk 'program'
awk applies the program to the standard input, which usually means whatever you type on the terminal. This continues until you indicate end-of-file by typing ctrl-d.
Example:
awk "BEGIN { print \"Don't Panic!\" }" 

This program does not read any input. The `\' before each of the inner double quotes is necessary because of the shell's quoting rules—in particular because it mixes both single quotes and double quotes


Running Long Programs
Sometimes your awk programs can be very long. In this case, it is more convenient to put the program into a separate file. In order to tell awk to use that file for its program, you type:


awk -f source-file input-file1 input-file2 ...
The -f instructs the awk utility to get the awk program from the file source-file. Any file name can be used for source-file. For example, you could put the program:
BEGIN { print "Don't Panic!" }
into the file advice. Then this command:
awk -f advice
does the same thing as this one:
awk "BEGIN { print \"Don't Panic!\" }"

Executable awk Programs


Once you have learned awk, you may want to write self-contained awk scripts, using the `#!' script mechanism. For example, you could update the file advice to look like this:
#! /bin/awk -f
     BEGIN { print "Don't Panic!" }

After making this file executable (with the chmod utility), simply type `advice' at the shell and the system arranges to run awk as if you had typed `awk -f advice':
chmod +x advice
     $ advice
     -| Don't Panic!

Comments in awk programs
In the awk language, a comment starts with the sharp sign character (`#') and continues to the end of the line. The `#' does not have to be the first character on the line. The awk language ignores the rest of a line following a sharp sign. For example, we could have put the following into advice:
# This program prints a nice friendly message.  It helps
     # keep novice users from being afraid of the computer.
     BEGIN    { print "Don't Panic!" }

Note: You
can enclose small to medium programs in single quotes, in order to
keep your shell scripts self-contained. When doing so, don't
put an apostrophe (i.e., a single quote) into a comment (or anywhere
else in your program)
For example, look at the following:


awk '{ print "hello" } # let's be cute'
     > '
     error--> awk: can't open file be
     error-->  source line number 1

Some simple Examples:
awk '/foo/ { print $0 }' BBS-list
This command runs a simple awk program that searches the input file BBS-list for the character string `foo'.When lines containing `foo' are found, they are printed because `print $0' means print the current line. Here is what this program prints:
awk '/foo/ { print $0 }' BBS-list
     -| fooey        555-1234     2400/1200/300     B
     -| foot         555-6699     1200/300          B
     -| macfoo       555-6480     1200/300          A
     -| sabafoo      555-2127     1200/300          C



Many practical awk programs are just a line or two. Following is a collection of useful, short programs to get you started.
Print the length of the longest input line:
awk '{ if (length($0) > max) max = length($0) }
END { print max }' data
Print every line that is longer than 80 characters: 
          awk 'length($0) > 80' data 


Print the length of the longest line in data:
expand data | awk '{ if (x < length()) x = length() }
                        END { print "maximum line length is " x }' 
Print every line that has at least one field: 
awk 'NF > 0' data
This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been removed).


Print seven random numbers from 0 to 100, inclusive: 
awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
Print  the total number of bytes used by files
ls -l files | awk '{ x += $5 } END { print "total bytes: " x }'
Print  the total number of kilobytes used by files
ls -l files | awk '{ x += $5 } END { print "total K-bytes: " (x + 1023)/1024 }'     
Print a sorted list of the login names of all users: 
awk -F: '{ print $1 }' /etc/passwd | sort
Count  the lines in a file: 
awk 'END { print NR }' data
Print the even-numbered lines in the data file:
awk 'NR % 2 == 0' data 
If you use the expression `NR % 2 == 1' instead, the program would print the odd-numbered lines.


If you want to view more examples, visit AWK Programming