Showing posts with label Unix Shell Programming. Show all posts
Showing posts with label Unix Shell Programming. Show all posts

Monday, 2 June 2014

Unix - Shell Manpage Help

Post By; Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Unix - Shell Manpage Help

All the Unix commands come with a number of optional and mandatory options. It is very common to forget complete syntax of these commands.
Because no one can possibly remember every Unix command and all its options, there has been online help available since Unix's earliest days.
Unix's version of help files are called man pages. If you know any command name but you do not know how to use it, then Man Pages are here to help you at every step.

Syntax:

Here is the simple command to get the detail of any Unix command while working with the system:
$man command

Example:

Now you imagine any command for which you want to get help. Assuming you want to know about pwdthen you simply need to use the following command:
$man pwd
The above command would open a help for you which would give you complete information about pwdcommand. Try it yourself at your command prompt to get more detail on
You can get complete detail on man command itself using the following command:
$man man

Man Page Sections:

Man pages are generally divided into sections, which generally vary by the man page author's preference. Here are some of the more common sections:
SectionDescription
NAMEName of the command
SYNOPSISGeneral usage parameters of the command.
DESCRIPTIONGenerally describes of the command and what it does
OPTIONSDescribes all the arguments or options to the command
SEE ALSOLists other commands that are directly related to the command in the man page or closely resembling its functionality.
BUGSExplains any known issues or bugs that exist with the command or its output
EXAMPLESCommon usage examples that give the reader an idea of how the command can be used.
AUTHORSThe author of the man page/command.
So finally, I would say that man pages are a vital resource and the first avenue of research when you need information about commands or files in a Unix system.

Posted By MIrza Abdul Hannan11:33:00 pm

Unix - Shell Functions

Post By; Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Unix - Shell Functions

Functions enable you to break down the overall functionality of a script into smaller, logical subsections, which can then be called upon to perform their individual task when it is needed.
Using functions to perform repetitive tasks is an excellent way to create code reuse. Code reuse is an important part of modern object-oriented programming principles.
Shell functions are similar to subroutines, procedures, and functions in other programming languages.

Creating Functions:

To declare a function, simply use the following syntax:
function_name () { 
   list of commands
}
The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, which are followed by a list of commands enclosed within braces.

Example:

Following is the simple example of using function:
#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World"
}

# Invoke your function
Hello
When you would execute above script it would produce following result:
$./test.sh
Hello World
$

Pass Parameters to a Function:

You can define a function which would accept parameters while calling those function. These parameters would be represented by $1, $2 and so on.
Following is an example where we pass two parameters Zara and Ali and then we capture and print these parameters in the function.
#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World $1 $2"
}

# Invoke your function
Hello Zara Ali
This would produce following result:
$./test.sh
Hello World Saira Qayyum
$

Returning Values from Functions:

If you execute an exit command from inside a function, its effect is not only to terminate execution of the function but also of the shell program that called the function.
If you instead want to just terminate execution of the function, then there is way to come out of a defined function.
Based on the situation you can return any value from your function using the return command whose syntax is as follows:
return code
Here code can be anything you choose here, but obviously you should choose something that is meaningful or useful in the context of your script as a whole.

Example:

Following function returns a value 1:
#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World $1 $2"
   return 10
}

# Invoke your function
Hello Zara Ali

# Capture value returnd by last command
ret=$?

echo "Return value is $ret"
This would produce following result:
$./test.sh
Hello World Saira Qayyum
Return value is 10
$

Nested Functions:

One of the more interesting features of functions is that they can call themselves as well as call other functions. A function that calls itself is known as a recursive function.
Following simple example demonstrates a nesting of two functions:
#!/bin/sh

# Calling one function from another
number_one () {
   echo "This is the first function speaking..."
   number_two
}

number_two () {
   echo "This is now the second function speaking..."
}

# Calling function one.
number_one
This would produce following result:
This is the first function speaking...
This is now the second function speaking...

Function Call from Prompt:

You can put definitions for commonly used functions inside your .profile so that they'll be available whenever you log in and you can use them at command prompt.
Alternatively, you can group the definitions in a file, say test.sh, and then execute the file in the current shell by typing:
$. test.sh
This has the effect of causing any functions defined inside test.sh to be read in and defined to the current shell as follows:
$ number_one
This is the first function speaking...
This is now the second function speaking...
$
To remove the definition of a function from the shell, you use the unset command with the .f option. This is the same command you use to remove the definition of a variable to the shell.
$unset .f function_name

Posted By MIrza Abdul Hannan11:31:00 pm

Unix - Shell Input/Output Redirections

Post By; Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Unix - Shell Input/Output Redirections

Most Unix system commands take input from your terminal and send the resulting output back to your terminal. A command normally reads its input from a place called standard input, which happens to be your terminal by default. Similarly, a command normally writes its output to standard output, which is also your terminal by default.

Output Redirection:

The output from a command normally intended for standard output can be easily diverted to a file instead. This capability is known as output redirection:
If the notation > file is appended to any command that normally writes its output to standard output, the output of that command will be written to file instead of your terminal:
Check following who command which would redirect complete output of the command in users file.
$ who > users
Notice that no output appears at the terminal. This is because the output has been redirected from the default standard output device (the terminal) into the specified file. If you would check users file then it would have complete content:
$ cat users
oko         tty01   Sep 12 07:30
ai          tty15   Sep 12 13:32
ruth        tty21   Sep 12 10:10
pat         tty24   Sep 12 13:07
steve       tty25   Sep 12 13:03
$
If a command has its output redirected to a file and the file already contains some data, that data will be lost. Consider this example:
$ echo line 1 > users
$ cat users
line 1
$
You can use >> operator to append the output in an existing file as follows:
$ echo line 2 >> users
$ cat users
line 1
line 2
$

Input Redirection:

Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file. As the greater-than character > is used for output redirection, the less-than character < is used to redirect the input of a command.
The commands that normally take their input from standard input can have their input redirected from a file in this manner. For example, to count the number of lines in the file users generated above, you can execute the command as follows:
$ wc -l users
2 users
$
Here it produces output 2 lines. You can count the number of lines in the file by redirecting the standard input of the wc command from the file users:
$ wc -l < users
2
$
Note that there is a difference in the output produced by the two forms of the wc command. In the first case, the name of the file users is listed with the line count; in the second case, it is not.
In the first case, wc knows that it is reading its input from the file users. In the second case, it only knows that it is reading its input from standard input so it does not display file name.

Here Document:

here document is used to redirect input into an interactive shell script or program.
We can run an interactive program within a shell script without user action by supplying the required input for the interactive program, or interactive shell script.
The general form for a here document is:
command << delimiter
document
delimiter
Here the shell interprets the << operator as an instruction to read input until it finds a line containing the specified delimiter. All the input lines up to the line containing the delimiter are then fed into the standard input of the command.
The delimiter tells the shell that the here document has completed. Without it, the shell continues to read input forever. The delimiter must be a single word that does not contain spaces or tabs.
Following is the input to the command wc -l to count total number of line:
$wc -l << EOF
	This is a simple lookup program 
	for good (and bad) restaurants
	in Cape Town.
EOF
3
$
You can use here document to print multiple lines using your script as follows:
#!/bin/sh

cat << EOF
This is a simple lookup program 
for good (and bad) restaurants
in Cape Town.
EOF	
This would produce following result:
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
The following script runs a session with the vi text editor and save the input in the file test.txt.
#!/bin/sh

filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands
If you run this script with vim acting as vi, then you will likely see output like the following:
$ sh test.sh
Vim: Warning: Input is not from a terminal
$
After running the script, you should see the following added to the file test.txt:
$ cat test.txt
This file was created automatically from
a shell script
$

Discard the output:

Sometimes you will need to execute a command, but you don't want the output displayed to the screen. In such cases you can discard the output by redirecting it to the file /dev/null:
$ command > /dev/null
Here command is the name of the command you want to execute. The file /dev/null is a special file that automatically discards all its input.
To discard both output of a command and its error output, use standard redirection to redirect STDERR to STDOUT:
$ command > /dev/null 2>&1
Here 2 represents STDERR and 1 represents STDOUT. You can display a message on to STDERR by redirecting STDIN into STDERR as follows:
$ echo message 1>&2

Redirection Commands:

Following is the complete list of commands which you can use for redirection:
CommandDescription
pgm > fileOutput of pgm is redirected to file
pgm < fileProgram pgm reads its input from file.
pgm >> fileOutput of pgm is appended to file.
n > fileOutput from stream with descriptor n redirected to file.
n >> fileOutput from stream with descriptor n appended to file.
n >& mMerge output from stream n with stream m.
n <& mMerge input from stream n with stream m.
<< tagStandard input comes from here through next tag at start of line.
|Takes output from one program, or process, and sends it to another.
Note that file descriptor 0 is normally standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).

Posted By MIrza Abdul Hannan11:29:00 pm

Unix - Shell Quoting Mechanisms

Post By; Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Unix - Shell Quoting Mechanisms

The Metacharacters:

Unix Shell provides various metacharacters which have special meaning while using them in any Shell Script and causes termination of a word unless quoted.
For example ? matches with a single charater while listing files in a directory and an * would match more than one characters. Here is a list of most of the shell special characters (also called metacharacters):
* ? [ ] ' " \ $ ; & ( ) | ^ < > new-line space tab
A character may be quoted (i.e., made to stand for itself) by preceding it with a \.

Example:

Following is the example which show how to print a * or a ?:
#!/bin/sh

echo Hello; Word
This would produce following result.
Hello
./test.sh: line 2: Word: command not found

shell returned 127
Now let us try using a quoted character:
#!/bin/sh

echo Hello\; Word
This would produce following result:
Hello; Word
The $ sign is one of the metacharacters, so it must be quoted to avoid special handling by the shell:
#!/bin/sh

echo "I have \$1200"
This would produce following result:
I have $1200
There are following four forms of quotings:
QuotingDescription
Single quoteAll special characters between these quotes lose their special meaning.
Double quoteMost special characters between these quotes lose their special meaning with these exceptions:
  • $
  • `
  • \$
  • \'
  • \"
  • \\
BackslashAny character immediately following the backslash loses its special meaning.
Back QuoteAnything in between back quotes would be treated as a command and would be executed.

The Single Quotes:

Consider an echo command that contains many special shell characters:
echo <-$1500.**>; (update?) [y|n]
Putting a backslash in front of each special character is tedious and makes the line difficult to read:
echo \<-\$1500.\*\*\>\; \(update\?\) \[y\|n\]
There is an easy way to quote a large group of characters. Put a single quote ( ') at the beginning and at the end of the string:
echo '<-$1500.**>; (update?) [y|n]'
Any characters within single quotes are quoted just as if a backslash is in front of each character. So now this echo command displays properly.
If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you whould preceed that using a backslash (\) as follows:
echo 'It\'s Shell Programming'

The Double Quotes:

Try to execute the following shell script. This shell script makes use of single quote:

VAR=ZARA
echo '$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]'
This would produce following result:
$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]
So this is not what you wanted to display. It is obvious that single quotes prevent variable substitution. If you want to substitute variable values and to make invert commas work as expected then you would need to put your commands in double quotes as follows:
VAR=ZARA
echo "$VAR owes <-\$1500.**>; [ as of (`date +%m/%d`) ]"
Now this would produce following result:
ZARA owes <-$1500.**>; [ as of (07/02) ]
Double quotes take away the special meaning of all characters except the following:
  • $ for parameter substitution.
  • Backquotes for command substitution.
  • \$ to enable literal dollar signs.
  • \` to enable literal backquotes.
  • \" to enable embedded double quotes.
  • \\ to enable embedded backslashes.
  • All other \ characters are literal (not special).
Any characters within single quotes are quoted just as if a backslash is in front of each character. So now this echo command displays properly.
If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you whould preceed that using a backslash (\) as follows:
echo 'It\'s Shell Programming'

The Back Quotes:

Putting any Shell command in between back quotes would execute the command

Syntax:

Here is the simple syntax to put any Shell command in between back quotes:

Example:

var=`command`

Example:

Following would execute date command and produced result would be stored in DATA variable.
DATE=`date`

echo "Current Date: $DATE"
This would produce following result:
Current Date: Thu Jul  2 05:28:45 MST 2009

Posted By MIrza Abdul Hannan11:26:00 pm