Shell Programming Blog Shell Programming Blog

Saturday, 22 September 2012

how to find out exit status of command or shell script?

Unknown | 11:16 | Be the first to comment!



By default in Linux if particular command/shell script is executed, it return two type of values which is used to see whether command or shell script executed is successful or not.

(1) If return value is zero (0), command is successful.
(2) If return value is nonzero, command is not successful or some sort of error executing command/shell script.


This value is know as Exit Status.

But how to find out exit status of command or shell script?
Simple, to determine this exit Status you can use $? special variable of shell. For e.g. (This example assumes that unkfile doest not exist on your hard drive)


$ rm unkfile

It will show error as follows
rm: cannot remove `unkowm1file': No such file or directory and after that if you give command


$ echo $?

It will print nonzero value to indicate error. Now give command


$ ls
$ echo $?

It will print 0 to indicate command is successful.


Exercise
Try the following commands and not down the exit status:
$ expr 1 + 3
$ echo $?


$ echo Welcome
$ echo $?

$ wildwest canwork?
$ echo $?

$ date
$ echo $?

$ echon $?
$ echo $?

Shell Built in Variables

Shell Built in VariablesMeaning
$#Number of command line arguments. Useful to test no. of command line args in shell script.
$*All arguments to shell
$@Same as above
$-Option supplied to shell
$$PID of shell
$!PID of last started background process (started with &)

 

Sunday, 9 September 2012

How to print or access value of UDV (User defined variables)

Unknown | 06:58 | Be the first to comment!


 


To print or access UDV use following syntax

Syntax:
$variablename

Define variable vech and n as follows:
$ vech=Bus
$ n=10


To print contains of variable 'vech' type
$ echo $vech

It will print 'Bus',To print contains of variable 'n' type command as follows
$ echo $n

Caution: Do not try $ echo vech, as it will print vech instead its value 'Bus' and $ echo n, as it will print n instead its value '10', You must use $ followed by variable name.

Exercise
Q.1.How to Define variable x with value 10 and print it on screen.
Q.2.How to Define variable xn with value Rani and print it on screen
Q.3.How to print sum of two numbers, let's say 6 and 3?
Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
Q.5.Modify above and store division of x and y to variable called z
Q.6.Point out error if any in following script


Answers : - 

Q.1.How to Define variable x with value 10 and print it on screen.
$ x=10
$ echo $x

Q.2.How to Define variable xn with value Rani and print it on screen
Ans.
$ xn=Rani
$ echo $xn

Q.3.How to print sum of two numbers, let's say 6 and 3
$ echo 6 + 3
This will print 6 + 3, not the sum 9, To do sum or math operations in shell use expr, syntax is as follows 
Syntax:
expr   op1   operator   op2
Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be
+ Addition
- Subtraction
/ Division
% Modular, to find remainder For e.g. 20 / 3 = 6 , to find remainder 20 % 3 = 2, (Remember its integer calculation)
\* Multiplication
$ expr 6 + 3
Now It will print sum as 9 , But
$ expr 6+3
will not work because space is required between number and operator (See Shell Arithmetic)

Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
Ans.
$x=20
$ y=5
$ expr x / y


Q.5.Modify above and store division of x and y to variable called z
Ans.
$ x=20
$ y=5
$ z=`expr x / y`
$ echo $z


Q.6.Point out error if any in following script


ERROR 1 is due to the space left between the equal to sign and the variable. This should not have spaces

ERROR 2 is due to the missing of $sign before the variable 'myno'

Following script should work now, after bug fix!




Rules for Naming variable name (Both UDV and System Variable)

Unknown | 06:27 | Be the first to comment!

(1) Variable name must begin with Alphanumeric character or underscore character (_), followed by one or more Alphanumeric character. For e.g. Valid shell variable are as follows
HOME
SYSTEM_VERSION
vech
no


(2) Don't put spaces on either side of the equal sign when assigning value to variable. For e.g. In following variable declaration there will be no error
$ no=10
But there will be problem for any of the following variable declaration:
$ no =10
$ no= 10
$ no = 10


(3) Variables are case-sensitive, just like filename in Linux. For e.g.
$ no=10
$ No=11
$ NO=20

$ nO=2
Above all are different variable name, so to print value 20 we have to use $ echo $NO and not any of the following
$ echo $no                 # will print 10 but not 20
$ echo $No                # will print 11 but not 20
$ echo $nO                # will print 2 but not 20

(4) You can define NULL variable as follows (NULL variable is variable which has no value at the time of definition) For e.g.
$ vech=
$ vech=""

Try to print it's value by issuing following command
$ echo $vech
Nothing will be shown because variable has no value i.e. NULL variable.

(5) Do not use ?,* etc, to name your variable names.

Variables in Linux shell

Unknown | 06:18 | Be the first to comment!


To process our data/information, data must be kept in computers RAM memory. RAM memory is divided into small locations, and each location had unique number called memory location/address, which is used to hold our data. Programmer can give a unique name to this memory location/address called memory variable or variable (Its a named storage location that may take different values, but only one at a time).

In Linux (Shell), there are two types of variable:

(1) System variables - Created and maintained by Linux itself. This type of variable defined in CAPITAL LETTERS.

(2) User defined variables (UDV) - Created and maintained by user. This type of variable defined in lower letters.

You can see system variables by giving command like $ set, some of the important System variables are:

System Variable
Meaning
BASH=/bin/bashOur shell name
BASH_VERSION=1.14.7(1)Our shell version name
COLUMNS=80No. of columns for our screen
HOME=/home/vivekOur home directory
LINES=25No. of columns for our screen
LOGNAME=studentsstudents Our logging name
OSTYPE=LinuxOur Os type
PATH=/usr/bin:/sbin:/bin:/usr/sbinOur path settings
PS1=[\u@\h \W]\$Our prompt settings
PWD=/home/students/CommonOur current working directory
SHELL=/bin/bashOur shell name
USERNAME=vivekUser name who is currently login to this PC


NOTE that Some of the above settings can be different in your PC/Linux environment. You can print any of the above variables contains as follows:
$ echo $USERNAME
$ echo $HOME

Exercise:
1) If you want to print your home directory location then you give command:
a)$ echo $HOME
OR
(b)$ echo HOME
Which of the above command is correct & why? 

Ans.: (a) command is correct, since we have to print the contains of variable (HOME) and not the HOME. You must use $ followed by variable name to print variables cotaines.

Caution: Do not modify System variable this can some time create problems.

How to define User defined variables (UDV)

To define UDV use following syntax

Syntax:
variable name=value
'value' is assigned to given 'variable name' and Value must be on right side = sign.

Example:

$ no=10            # this is ok
$ 10=no            # Error, NOT Ok, Value must be on right side of = sign.

To define variable called 'vech' having value Bus
$ vech=Bus

To define variable called n having value 10
$ n=10

Saturday, 8 September 2012

vi editor Command list in Linux

Unknown | 19:15 | Be the first to comment!

We have lot of commands that we can  use inside a vi editor in Linux. Out of which, I have listed a few common commands that we can use in vi editor for creating a shell script or any other document.


 For this PurposeUse this vi Command Syntax
To insert new textesc + i ( You have to press 'escape' key then 'i')
To save fileesc + : + w (Press 'escape' key  then 'colon' and finally 'w')
To save file with file name (save as)esc + : + w  "filename"
To quit the vi editoresc + : + q
To quit without savingesc + : + q!
To save and quit vi editoresc + : + wq
To search for specified word in forward directionesc + /word (Press 'escape' key, type /word-to-find, for e.g. to find word 'shri', type as
/shri)
To continue with search n
To search for specified word in backward directionesc + ?word (Press 'escape' key, type word-to-find)
To copy the line where cursor is locatedesc + yy
To paste the text just deleted or copied at the cursoresc + p
To delete entire line where cursor is locatedesc + dd
To delete word from cursor positionesc + dw
To Find all occurrence of given word and Replace then globally without confirmation esc + :$s/word-to-find/word-to-replace/gFor. e.g. :$s/mumbai/pune/g
Here word "mumbai" is replace with "pune"
To Find all occurrence of given word and Replace then globally with confirmationesc + :$s/word-to-find/word-to-replace/cg
To run shell command like ls, cp or date etc within viesc + :!shell-command

For e.g. :!pwd

Let me know if you need more details or explanation on any particular topics in Shell scritping.

How to write a shell script

Unknown | 19:11 | Be the first to comment!

Following steps are required to write shell script:
  1. Use any editor like vi or mcedit to write shell script.
  2. After writing shell script set execute permission for your script as follows
syntax:
chmod permission your-script-name

Examples:
$ chmod +x your-script-name
$ chmod 755 your-script-name


Note: This will set read write execute(7) permission for owner, for group and other permission is read and execute only(5). 

    3.  Execute your script as

syntax:
bash your-script-name
sh your-script-name
./your-script-name


Examples:
$ bash bar
$ sh bar
$ ./bar


NOTE: In the last syntax ./ means current directory, But only . (dot) means execute given command file in current shell without starting the new copy of shell, The syntax for . (dot) command is as follows
Syntax:
. command-name

Example:
$ . foo

Now you are ready to write first shell script that will print "Hello World" on screen (As we do it all programming languages; I always wonder why?? :P)  See the common vi command list , if you are new to vi




After saving the above script, you can run the script as follows:
$ ./first

This will not run script since we have not set execute permission for our script first; to do this type command
$ chmod 755 first
$ ./first


First screen will be cleared, then Hello World is printed on screen.

Let me know if you need more details or explanation on any particular topics in Shell scritping.

What is Shell Script and why do we need it?

Unknown | 18:43 | Be the first to comment!



What is Shell script?

Shell Script is series of command written in plain text file. Shell script is just like batch file is MS-DOS but have more power than the MS-DOS batch file.

Why to Write Shell Script ?
  1.     Shell script can take input from user, file and output them on screen.
  2.     Useful to create our own commands.
  3.     Save lots of time.
  4.     To automate some task of day today life.
  5.     System Administration part can be also automated.

A shell script to validate the given text

Unknown | 11:25 | Be the first to comment!

This script will ensure that the given text contains only Alphabets and numeric characters



Please let me know your doubts or questions. I will clarify them.

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming