Saturday, April 11, 2009

Input-Output redirection on linux

Whenever you issue "ls" command on the console and press enter you see it's output is on your console. Sometimes you may wish to redirect the output to your file. With the ">" command you can send output to an OS file. Several redirector symbol along with examples are discussed below.

1)< Redirector symbol:
Usage syntax is
linux_commnads< filename
The output of linux_commands will be written to file filename.

Note that, if the file does not exist in the location, a new file will be created and if the file already exist in the location it will be overwritten.

Example:
# ls>ls_output.txt

# ls
command.sh ls_output.txt quote.sh test_echo.bash test_user.txt t_sep.sh
echo.sh practice read.sh test_echo.sh test_v.sh

# cat ls_output.txt
command.sh
echo.sh
ls_output.txt
practice
quote.sh
read.sh
test_echo.bash
test_echo.sh
test_user.txt
test_v.sh
t_sep.sh

Be cautious of the filename when redirecting output to a file. If filename already exist it will be overwritten.

2)>> Redirector Symbol:
>> redirector symbol works just like > but in this case if file already exist, data will be appended to the end of the file. If file is not there, then as of > symbol, >> symbol also create a new file and write data into it.
Example:
Let's see the contents inside ls_output.txt file.
# cat ls_output.txt
command.sh
echo.sh
ls_output.txt
practice
quote.sh
read.sh
test_echo.bash
test_echo.sh
test_user.txt
test_v.sh
t_sep.sh

Append output of ls -a to the end of the file ls_output.txt
# ls -a>>ls_output.txt

Let's see what ls -a do. It does not ignore directory contents with . enties.
# ls -a
. command.sh ls_output.txt quote.sh test_echo.bash test_user.txt t_sep.sh
.. echo.sh practice read.sh test_echo.sh test_v.sh

Let's see contents of ls_output.txt and we see output of ls -a is appended to the end.

# cat ls_output.txt
command.sh
echo.sh
ls_output.txt
practice
quote.sh
read.sh
test_echo.bash
test_echo.sh
test_user.txt
test_v.sh
t_sep.sh
.
..
command.sh
echo.sh
ls_output.txt
practice
quote.sh
read.sh
test_echo.bash
test_echo.sh
test_user.txt
test_v.sh
t_sep.sh

3)< Redirector Symbol
> redirector symbol is used to direct output to a file and < redirector is used to read contents from a file. In order to make it clear let's create a file named names.txt and below is it contents.
# cat names.txt
momin
arju
bony
tany
azmeri
queen
tasreen

Now my target is to sort the names inside names.txt and save the sorted order into another file named names_sorted.txt
# sort <names.txt>names_sorted.txt
By above command the sorted output will be stored into names_sorted.txt. If we would only type the first part sort<names.txt then it would simply sort the names inside txt and display to console as below.
#sort<names.txt

arju
azmeri
bony
momin
queen
tany
tasreen

with > redirection we would not let it happen to display on console rather redirect output to a file named names_sorted.txt.


# cat names_sorted.txt


arju
azmeri
bony
momin
queen
tany
tasreen

Similarly if you want to make all letters inside the file names_sorted.txt into uppercase then we can do it with tr command (which will translates all lowercase letter into uppercase). Below is such an example.

# tr "[a-z]" "[A-Z]" <names_sorted.txt>names_uppercase.txt
# cat names_uppercase.txt


ARJU
AZMERI
BONY
MOMIN
QUEEN
TANY
TASREEN

Important Tips
Note that, each program you run on linux (line ls, rm or anything) access to three important files. You can add parameter(1 or 2 or 3) in order to get information about particular things while running any command.

These files are standard input, standard output and standard error file. And each of the files (standard input, output and error) have the file descriptors 0, 1 and 2 respectively. With while you do command you can pass 1 or 2 or 3 in order to get information of certain type information.

0=Standard Input
1=Standard Output
2=Standard Error


An example will make you clear.
Whenever you issue ls b.txt it says no file on the console.
# ls b.txt
ls: b.txt: No such file or directory

Whenever you add 1 with ls command and redirect output then in the output file there is nothing as no expected result came rather than an error generated.
# ls b.txt 1>output_b.txt
ls: b.txt: No such file or directory

# cat output_b.txt

However if we want to catch the error then we have to add 2 with the command as below.
# ls b.txt 2>output_b.txt

# cat output_b.txt
ls: b.txt: No such file or directory

Related Documents

http://arjudba.blogspot.com/2009/04/arithmatic-operation-and-expression-in.html

http://arjudba.blogspot.com/2009/04/system-notes-org-how-to-copy-and-paste.html

Command writing, command line arguments in shell script

Command writing inside shell script
Unlike any other scripting language or programming language a statement inside shell script need not to be ended with semicolon (;).
If you press newline(i.e enter button from your keyboard) after a statement then shell script automatically determines another statement.
However, if you want to include two statements in one line then you have to separate by them by comma(;).

# vi t_sep.sh
ls -l;pwd

# chmod +x t_sep.sh

# ./t_sep.sh

total 36
-rwxr-xr-x 1 root root 67 Apr 10 03:00 echo.sh
drwxr-xr-x 2 root root 4096 Apr 11 09:08 practice
-rwxr-xr-x 1 root root 106 Apr 10 11:06 quote.sh
-rwxr-xr-x 1 root root 104 Apr 11 04:30 read.sh
-rwxr-xr-x 1 root root 177 Apr 10 03:33 test_echo.bash
-rwxr-xr-x 1 root root 325 Apr 6 10:45 test_echo.sh
-rwxrwxrwx 1 root root 569 Apr 6 12:23 test_user.txt
-rwxr-xr-x 1 root root 41 Apr 9 07:48 test_v.sh
-rwxr-xr-x 1 root root 10 Apr 11 11:37 t_sep.sh
/home/arju/test
See after ls -l command, pwd command is executed.

Command line Arguments and $#,$@,$*,$0
Whenever you run script you can pass arguments to the script from command line. Those command line arguments can tracked.

With $# you can count the number of arguments specified on command line. Number count (starts from 1) is the total number of arguments except shell script name.

With $@ or $* you can refer to the argument of the command line.

With $0, $1 , $2 etc. you can access the first argument, second argument, third argument corresponds on the command line. Note that, $0 indicates the shell script name that is specified first while tunning shell script.

# cat command.sh
echo -n 'The list of arguments $*:'
echo $*
echo -n 'The number of arguments $#:'
echo $#
echo -n 'The list of arguments $@:'
echo $@
echo -n 'First Argument $0:'
echo $0
echo -n 'Second Argument $1:'
echo $1
echo -n 'Third Argument $2:'
echo $2

# chmod +x command.sh

# ./command.sh first second 100

The list of arguments $*:first second 100
The number of arguments $#:3
The list of arguments $@:first second 100
First Argument $0:./command.sh
Second Argument $1:first
Third Argument $2:second
Related Documents

Wildcard characters in linux

In linux there is wildcard characters *, ? and pair of bracket [] by which we can filter the output. Below is the usage of the wildcard characters in linux along with their examples.

1)* : * shows the matches any string or group of characters.
Example:

# ls
echo.sh quote.sh read.sh test_echo.bash test_echo.sh test_user.txt test_v.sh

test* shows the string that starts with test.

# ls test*
test_echo.bash test_echo.sh test_user.txt test_v.sh

t*er* shows string that starts with character t followed by any character or null, then er and then any strings.

# ls t*er*
test_user.txt

2)? : ? shows the matches of any single character. Note that instead of ? just only a any single character can be replaceable. For example if you write arju? then total string will be of length 5 like arjua , arjub etc. Below is an example,

# ls
arju arjua arjub

# ls arju?
arjua arjub

3)[] : The character within third bracket ([]) indicates any single character within the bracket to be matched. Suppose, if you write arju[ad] then only it will match the strings start with arju and then end with either a or d. Note that it to be matched with any single character within bracket but not both. Below is an example.

# ls
arju arjua arjuad arjub arjud

# ls arju[ad]
arjua arjud

Within bracket you can also include minus (-) sign between two characters to define a range. Below is an example.
# ls
arju bony richard robert zaman

# ls ?[o-z]*
arju bony robert

Here with [o-z] we define a range which means character start with o and ends with z, so o,p,q,r,s.....z falls within this range. We want 2nd character in the example to be fall under the range of [o-z] and thus filtered output of ls.

We can revert the search range of the characters between bracket by using ! or ^ sign just after starting left bracket.
For example if we use ls ?[!o-z]* or ls ?[^o-z]* then it will behave reverse of filter [o-z].
Example:

# ls
arju bony richard robert zaman

# ls ?[!o-z]*
richard zaman

# ls ?[^o-z]*
richard zaman

In both cases if the 2nd character inside string does not fall within range (o-z) (o,p,q,r,....y,z) then that characters will be displayed.
Related Documents
http://arjudba.blogspot.com/2009/04/rules-for-naming-variable-name-in-unix.html
http://arjudba.blogspot.com/2009/04/arithmatic-operation-and-expression-in.html

Friday, April 10, 2009

Basic shell programming commands quote, exit, read

About Quotes
In shell programming you might want to use frequently three types of quotes.

1)Double Quotes ("") : Anything you write inside double quotes that is treated as themselves except dollar sign ($) and backslash (\).

2)Single Quotes (') : Anything you write inside double quotes that is treated as themselves. All remain unchanged.

3)Back Quotes (`) : Back quote is used to execute commands. If we want to execute any command inside shell script that must be inside back quotes.

Below is an example with these three types of quote.

Tahaa2:/home/arju/test# cat t_quote.sh
variable=10
echo "This is variable $variable"
echo 'This is variable $variable'
echo "This is pwd `pwd`"

Tahaa2:/home/arju/test# chmod +x t_quote.sh
Tahaa2:/home/arju/test# ./t_quote.sh
This is variable 10
This is variable $variable
This is pwd /home/arju/test

In the example note that in case of double quotes(") value of variable is shown but in case of single quotes(') variable name itself shown as it was inside single quotes. And for backquotes `pwd` command is executed and shown on the console.

Exit status $?
After every command or shell script executed on linux, it always returns the status of the command whether command is executed successfully or not. If command is executed sucessfully then exit status become zero, but if command is not executed successfully then exit status become non-zero value. We can check the exit status by $? sign.
Below is an example:

Tahaa2:/home/arju/test# ls nofile.txt
ls: nofile.txt: No such file or directory
Tahaa2:/home/arju/test# echo $?
2

Tahaa2:/home/arju/test# rm nofileexist.txt no_file.bat
rm: cannot lstat `nofileexist.txt': No such file or directory
rm: cannot lstat `no_file.bat': No such file or directory
Tahaa2:/home/arju/test# echo $?
1

Tahaa2:/home/arju/test# echo $?
0

Read data from console
With the "read" statement you can read input data from keyboard and store it in variable. Later you can process, work and display this variable.
Below is an example of read.
Tahaa2:/home/arju/test# vi t_read.sh
echo -n "Please eneter your name: "
read name
echo "Welcome $name to the http://arjudba.blogspot.com "
Tahaa2:/home/arju/test# chmod +x t_read.sh
Tahaa2:/home/arju/test# ./t_read.sh
Please eneter your name: Robert
Welcome Robert to the http://arjudba.blogspot.com

Related Documents
http://arjudba.blogspot.com/2009/04/rules-for-naming-variable-name-in-unix.html
http://arjudba.blogspot.com/2009/04/arithmatic-operation-and-expression-in.html

Rules for naming variable name in Unix

Before coding shell script it is very important that you would have an idea about the rules of the naming variable name in unix. You should need special care about this post because in shell script naming of variables are different than other usual programming language. Step by steps rules are discussed.

1)Variable names must begin with underscore or any alphanumeric characters. Never use ?,*,#,$ etc to name your variables.

Following is valid variable name.
username
password


2)While assigning value to a variable never use space on the either side of the equal sign(=).
The following one is valid,
a=20
But the followings are invalid as there is space after or before equal sign.
a= 20
a =20
a = 20

Assigning value in this way (space before or after equal) will cause error "command not found".

3)While comparing value with a variable note that between comparison operator there must space and also between bracket and variable there is space.
The following one is valid,
if [ $v = 10 ]
But the followings are invalid as there is no space between bracket and variable or between comparison operator and variable.
if [ $v=10 ]
if [$v = 10]
if [$v =10 ]

are invalid.

4)As of linux file system variables are case sensitive. So num and Num are different.

5)In order to assign a null value to a variable you can do following. You can assign null value to a variable at the time of variable declaration.
To assign null value to a variable test issue,
test=
or,
test=""
Related Documentation

Arithmetic operation and expression in shell script with expr

With expr you can evaluate expression and can do arithmatic operations.
The syntax of using expr is below:
expr operand1 operator operand2

Note that there is a space between the operator and the both operands.

The list of the operator is discussed below.
1)"|": Usage syntax is ARG1 | ARG2 and result is the ARG1 if it is neither null nor 0, otherwise reult is ARG2.
Example:

Tahaa2:/home/arju/test# expr 10 \| 0
10
Tahaa2:/home/arju/test# expr 0 \| 12
12

Note that as | is a special character so escape character (\) is needed before to use them.

2)"&": Usage syntax is ARG1 & ARG2 and result is the ARG1 if neither argument is null or 0, otherwise 0.
Example:

Tahaa2:~# expr "" \& 12
0
Tahaa2:~# expr 7 \& 12
7

Note that as & is a special character so escape character (\) is needed before to use them.

3)"<" : Usage syntax is ARG1 < ARG2 and result is 1 if ARG1 is less than ARG2, otherwise result is 0.

Tahaa2:~# expr 7 \< 12
1
Tahaa2:~# expr 12 \< 7
0

4)"<=": Usage syntax is ARG1 <= ARG2 and result is 1 if ARG1 is less than or equal to ARG2, otherwise result is 0.

Tahaa2:~# expr 0 \<= 0
1
Tahaa2:~# expr 0 \<= -8
0

5)"=" : Usage syntax is ARG1 = ARG2 and result is 1 if ARG1 is equal to ARG2, otherwise result is 0.

Tahaa2:~# expr 0 = 1
0
Tahaa2:~# expr 0 = 0
1

6)"!=" : Usage syntax is ARG1 != ARG2 and result is 1 if ARG1 is not equal to ARG2, otherwise result is 0.

Tahaa2:~# expr "0" != 0
0
Tahaa2:~# expr "0" != 10
1

7)">=" : Usage syntax is ARG1 >= ARG2 and result is 1 if ARG1 is greater than or equal to ARG2, otherwise result is 0.
Example:

Tahaa2:~# expr 23 \>= 24
0
Tahaa2:~# expr 1 \>= 1
1

8)">" : Usage syntax is ARG1 > ARG2 and result is 1 if ARG1 is greater than ARG2, otherwise result is 1.
Example:

Tahaa2:~# expr 23 \> 24
0
Tahaa2:~# expr 1 \> -1
1


9)"+" : Arithmetic sum of the two operands.

Tahaa2:/home/arju/test# expr 5 + 6
11

10)"-" : Arithmetic difference of the two operands.

Tahaa2:/home/arju/test# expr 5 - 6
-1

11)"*" : Arithmetic product of the two operands.

Tahaa2:~# expr 7 \* 8
56

12)"/" : Usage syntax is ARG1 / ARG2 and result is the arithmetic quotient of ARG1 divided by ARG2.

Tahaa2:~# expr 7 / 8
0
Tahaa2:~# expr 78 / 8
9

13)"%" : Usage syntax is ARG1 % ARG2 and result is the arithmetic remainder of ARG1 divided by ARG2.

Tahaa2:~# expr 78 % 8
6

14)length STRING : Returns the length of the string.
Example:

Tahaa2:~# expr length " This is normal Text"
20

15)index STRING CHARS: Return the indexing number of the CHARS in STRING if found, otherwise returns 0. Note that numbering start from 1. If there is multiple characters inside STRING of CHARS then first index number is returned. And also first characters of CHARS is evaluated.
Example:

Tahaa2:~# expr index "Arju, Robert, Richard" "R"
7

first one of R position is return.

Tahaa2:~# expr index "Arju, Robert, Richard" "Ri"
7

Position of R is returned, not of i.

Tahaa2:~# expr index "Arju, Robert, Richard" "c"
17
Tahaa2:~# expr index "Arju, Robert, Richard" ","
5

16) substr STRING POS LENGTH : It returns substring of STRING, starting from POS and string length of LENGTH. Note that position starts from 1.

Tahaa2:~# expr substr "Arju, Robert, Richard" 6 7
Robert

In the example from the string, from position 6 (i.e space) upto 7 lengths of characters are returned.

17)match STRING REGEXP : Anchored pattern match of REGEXP in STRING. Can also be expressed as STRING : REGEXP
Example:

Tahaa2:~# expr match "Arju, Robert, Richard" "Arju "
0
Tahaa2:~# expr match "Arju, Robert, Richard" "Arju,"
5

Related Documents
http://arjudba.blogspot.com/2009/04/system-notes-org-how-to-copy-and-paste.html
http://arjudba.blogspot.com/2009/04/what-is-kernel-shell-shell-script.html
http://arjudba.blogspot.com/2009/04/basic-steps-to-write-shell-script.html

Thursday, April 9, 2009

Displaying text with echo command

With echo command on unix you can display text to console.
The syntax is to use echo command is,

echo [options] ... [strings] ...

The strings contains the text to display and it would be within double quotes.
With options you can control how output will be displayed on console. In option section you can provide -n or -e or -E option.

If you use -n option, then after displaying strings new line will not be printed. By default if you use echo without -n options then after displaying strings trailing newline is printed.

If you use -e option, then while displaying strings any backslash character is interpreted as escape character. By default if you use echo without -e option backslash is printed if it is within string.

If you use -E option, then backslash character is not termed as escape character which is the default behavior of echo.

As with -e option of echo backslash (\) is interpreted as escape character so as -e is in effect, the following sequences can be used to print special output.


\0NNN the character whose ASCII code is NNN (octal)
\\ backslash
\a alert (BEL)
\b backspace
\c suppress trailing newline
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab

Below is an script that shows an example of echo.

Tahaa2:/home/arju/test# vi test_echo.bash
echo "This is normal echo without option"
echo "Bacslah (\) will be printed"
echo -n "New line will not be printed after end of line:"
echo "5"
echo -e "Special \n t\te\tx\tt"

Tahaa2:/home/arju/test# chmod +x test_echo.bash

Tahaa2:/home/arju/test# ./test_echo.bash
This is normal echo without option
Bacslah (\) will be printed
New line will not be printed after end of line:5
Special
t e x t

Related Documents
http://arjudba.blogspot.com/2009/04/system-notes-org-how-to-copy-and-paste.html
http://arjudba.blogspot.com/2009/04/what-is-kernel-shell-shell-script.html
http://arjudba.blogspot.com/2009/04/basic-steps-to-write-shell-script.html

Wednesday, April 8, 2009

Variables in shell

In linux there are two types of variables. These two types of variable is used in shell as well as shell script.

1)System variables: These variables are created and maintained by linux itself. From shell script we can use these variables in order to different types of helps. System variables are upper case.

2)User defined variables: These types of variables are created and maintained by user. In shell script you define it as yourself in order to manage the code. Normally user defined variables are declared as lowercase.

You can see any system variables or user defined variables by,
echo $VARIABLE_NAME
command. Where VARIABLE_NAME is the variable name that you wish to see.

You can set your system defined variable by export or setenv command based on your shell type.
On bash shell use, export VARIABLE_NAME=value
On c shell use, setenv VARIABLE_NAME=value

In order to see all the system variables defined on the system you can use set command like below.

arju:~# set
BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="3" [1]="1" [2]="17" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")
BASH_VERSION='3.1.17(1)-release'
CMN=/usr/unsafe/dev/common
COLUMNS=80
CONF=/etc/apache/httpd.conf
CVS_RSH=ssh
DIRSTACK=()
EDITOR=/usr/bin/vim
EUID=0
GDC=/usr/local/install/gdc
GROUPS=()
G_BROKEN_FILENAMES=1
HISTFILE=/root/.bash_history
HISTFILESIZE=1000
HISTSIZE=1000
HOME=/root
HOSTNAME=arju
HOSTTYPE=x86_64
IFS=$' \t\n'
INPUTRC=/etc/inputrc
INST=/usr/local/install
ISCMN=/usr/unsafe/dev/isuite/common
KDEDIR=/usr
KDE_IS_PRELINKED=1
KDE_NO_IPV6=1
LANG=en_US.UTF-8
LD_LIBRARY_PATH=:/usr/local/lib
LESSOPEN='|/usr/bin/lesspipe.sh %s'
LINES=24
LOG=/var/log
LOGNAME=root
MACHTYPE=x86_64-redhat-linux-gnu
MAIL=/var/spool/mail/root
MAILCHECK=60
NXDIR=/usr/NX
OLDPWD=/home/arju/test
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/lib64/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/NX/bin:/usr/local/etc/misc:/usr/contrib/bin:/usr/contrib/bin/infosec:/usr/local/sbin:/usr/local/bin:/bin:/usr/local/install/gdc/bin:/usr/local/install/ioncube:/root/bin
PHPLIB=/usr/safe/phplib
PIPESTATUS=([0]="0")
PKGS=/usr/local/packages
PPID=11601
PRELINKING=yes
PRELINK_FULL_TIME_INTERVAL=14
PRELINK_NONRPM_CHECK_INTERVAL=7
PRELINK_OPTS=-mR
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007"'
PS1='arju:\w# '
PS2='> '
PS4='+ '
PWD=/root
QTDIR=/usr/lib64/qt-3.3
QTINC=/usr/lib64/qt-3.3/include
QTLIB=/usr/lib64/qt-3.3/lib
SAFE=/usr/safe
SETUP=/etc/profile.d/zBiztek
SHELL=/bin/bash
SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
SHLVL=1
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SSH_CLIENT='113.11.14.16 2195 22'
SSH_CONNECTION='113.11.14.16 2195 192.168.100.18 22'
SSH_TTY=/dev/pts/0
TANGO=/usr/local/install/gdc/include/d/4.1.1/tango
TERM=xterm
UID=0
ULEM=/usr/local/etc/misc
USER=root
WEB=/usr/safe/websites
_=echo
consoletype=pty
qt_prefix=/usr/lib64/qt-3.3

Below is the description of major system variables.
1)BASH: Which contains the location of bash shell.
# echo $BASH
/bin/bash

2)BASH_VERSION: Which shows the bash shell version information.
# echo $BASH_VERSION
3.1.17(1)-release

3)COLUMNS: Which contains number of columns for the screen.
# echo $COLUMNS
80

4)HOME: Which contains the home directory location of the user.
# echo $HOME
/root

5)LINES: Which contains the number of columns in the screen.
# echo $LINES
24

6)LOGNAME: Which holds the username who is logging to the system.
# echo $LOGNAME
root

7)OSTYPE: Which holds the OS type information.
# echo $OSTYPE
linux-gnu

8)PATH: PATH variable contains the search path of all binary files. Two different locations are separated by colon (:).
# echo $PATH
/usr/lib64/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

9)PS1: Contains the information about what would be the prompt settings.
arju:/home/arju# echo $PS1
arju:\w#

If you change directory to test your prompt also to be changed.
# cd test
arju:/home/arju/test#

10)PWD: Contains current directory location.
# echo $PWD
/home/arju/test

11)SHELL: Shows information of shell that you are using.
# echo $SHELL
/bin/bash

12)USER: Contains username who is logging.
# echo $USER
root

Note that to see/access variable you have to use prepend "$" with the variable name. But to assign values to the variable you must not prepend "$".

# echo PWD # As we did not prepend $ so PWD is shown on screen.
PWD

Note that on unix/linux, after hash sign (#) rest of things are considered as comments.
Related Documents
http://arjudba.blogspot.com/2009/04/basic-steps-to-write-shell-script.html
http://arjudba.blogspot.com/2009/04/what-is-kernel-shell-shell-script.html
http://arjudba.blogspot.com/2009/04/simple-shell-script-to-check-whether.html

Tuesday, April 7, 2009

Basic steps to write a shell script

Below is the step by step procedure of how to write shell script and to execute them.

Step 01 - Create a shell script:
Creating a shell script is done as you create any other plain text files. Normally one use any text editor like vi/vim or emacs to create a shell script. To make easy identification of shell script you can give extension of shell script as .sh or .bash
For example, to create a shell script named test.sh issue,

#vi test.sh
or,
#vim test.sh

Step 02 - Give executable permission to shell script:
After creating shell script you need to assign executable permission to the script. It is necessary step to execute the script. Based the executable permission user must have the read permission of the script who will run the script.
You can give the execute permission of test.sh by two ways.

#chmod +x test.sh
or,
#chmod 755 test.sh

Step 03 - Execute the script:
After giving execute permission to the script you can then execute it. With bash or sh or simple dot (.) you can run your shell script.
For example to run the test.sh you can issue,
#bash test.sh
or,
#sh test.sh
or,
#./test.sh

Debugging a script
While writing shell scripts you need to find errors in it i.e debug the shell script and need to correct the errors. The -v and -x option with sh/bash is really useful to debug the script.

The -v option is used to print shell commands as they are read along with the outcome of the script. So if after some command if see desired output is not coming you can note down that commands.

The -x option is used for expanding each command. It displays the command, system variable and then its expanded arguments.

Below is my sample test_echo.sh script which I see how debugging look like.

arju:/home/arju/test# cat test_echo.sh
#!/bin/bash
echo "Warning! You are installing the Fall Creek portal software"
echo -n "Enter the product installation directory: "
read InstallDir
if [ "$InstallDir" = "" ]; then

InstallDir=`pwd`
echo "$InstallDir is used as Fall Creek business portal installation directory."

fi
echo "$InstallDir"

With using -v option.

arju:/home/arju/test# sh -v test_echo.sh
#!/bin/bash
echo "Warning! You are installing the Fall Creek portal software"
Warning! You are installing the Fall Creek portal software
echo -n "Enter the product installation directory: "
Enter the product installation directory: read InstallDir

if [ "$InstallDir" = "" ]; then

InstallDir=`pwd`
echo "$InstallDir is used as Fall Creek business portal installation directory."

fi
pwd
/home/arju/test is used as Fall Creek business portal installation directory.
echo "$InstallDir"
/home/arju/test

With using both -v and -x option.

arju:/home/arju/test# sh -vx test_echo.sh
#!/bin/bash
echo "Warning! You are installing the Fall Creek portal software"
+ echo 'Warning! You are installing the Fall Creek portal software'
Warning! You are installing the Fall Creek portal software
echo -n "Enter the product installation directory: "
+ echo -n 'Enter the product installation directory: '
Enter the product installation directory: read InstallDir
+ read InstallDir

if [ "$InstallDir" = "" ]; then

InstallDir=`pwd`
echo "$InstallDir is used as Fall Creek business portal installation directory."

fi
+ '[' '' = '' ']'
pwd
++ pwd
+ InstallDir=/home/arju/test
+ echo '/home/arju/test is used as Fall Creek business portal installation directory.'
/home/arju/test is used as Fall Creek business portal installation directory.
echo "$InstallDir"
+ echo /home/arju/test
/home/arju/test

Related Documents
http://arjudba.blogspot.com/2009/04/what-is-kernel-shell-shell-script.html

Monday, April 6, 2009

What is kernel, shell, shell script

Kernel
The linux kernel is the most important part or in order word called the heart of the linux operating system. It is the piece of code that manages both hardware and software components and communicates between them. It manages memory, processors, I/O devices with any applications and decides which applications will use hardware resources.

Shell
On your windows machine you have seen command prompt (command.com or cmd.exe) where you type command like ping, ipconfig etc. Similarly, on linux there is such prompt where you can type command and that prompt is called shell. In order to define shell we can say shell is an interpreter that interprets commands as typed from a keyboard or from a text script.

The shell is provided in order to interact with the computer systems. Shell itself is not part of the kernel, but it uses kernel to executes commands.

Shell interprets user commands, not compile them. It reads commands from the script per line and execute the commands, while a compiler converts a program into machine readable form, an executable file - which may then be used in a shell script.

There are various types of shell and can be broadly defined into four categories.

1)Bourne like shell(sh): Almquist shell (ash), Bourne-Again shell (bash), Debian Almquist shell (dash), Korn shell (ksh), Z shell (zsh) falls into bourne like shell category.

2)C shell like (csh): TENEX C shell (tcsh) falls within this category.

3)Non traditional shell: es shell (es), scheme Shell (scsh) falls within this category.

4)Historical shell: Thompson shell (sh), PWB shell or Mashey shell (sh) falls within this category.

In order to know all available shells in your system issue, cat /etc/shells
On my system,
# cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/tcsh
/bin/csh

To find out current shell you are using issue, echo $SHELL or ps $
On my system,

# ps $$
PID TTY STAT TIME COMMAND
4593 pts/0 Ss 0:00 -bash
# echo $SHELL
/bin/bash

The default shell for a user is mentioned within /etc/passwd file. For example to know the default shell of a user named arju issue,
# cat /etc/passwd |grep arju
arju:x:522:522::/home/arju:/bin/bash

To switch from one shell to another shell just write the name of the shell in the shell prompt.

For example to switch into bash shell issue,
#bash

To switch into TENEX C shell issue,
#tcsh

Shell Script
Shell script is a plain text file which contains a series of commands. In this case instead of running command one by one we can store all commands in a script and we execute the script. It is similar to a batch file in MS-DOS.

Related Documents
Introduction -What is kernel, shell, shell script.
Basic Steps to write a shell script
Variables in shell script
Output text with echo command
Arithmetic operation and expression in shell script with expr
Basic shell programming commands quote, exit and read

Linux Shell Script Tutorial

Chapter 1: Getting started with shell scripting
1. Introduction -What is kernel, shell, shell script.
2. Basic Steps to write a shell script
3. Variables in shell script
4. Output text with echo command
5. Arithmetic operation and expression in shell script with expr
6. Basic shell programming commands quote, exit and read
7. Wildcard characters in linux
8. Assignment and comparison variable in shell script
9. Command writing, command line arguments in shell script
10. Input-Output rediection on linux
11. Pipe with example in linux

Chapter 2: Shells Structured Language Constructs
1. If construct in shell script
2. Checking condition in shell scipt by test or [expr]
3. If else construct in shell script
4. For and while loop in shell script
5. Case statement in shell script

Chapter 3: Essential Shell Scripting Commands
1. What is /dev/null on linux
2. Conditional execution && and || in shell script
3. Functions in shell script
4. Trap command on linux shell script
5. The shift command and uses of it in shell script
6. getopts command in linux shell script

Chapter 4: Essential Utilities
1. Retrieve column from file using cut utility in linux
2. Merge lines using paste utility on linux
3. Join utility in linux
4. Translate or replace characters using tr utility
5. Data manipulation using awk utility in linux
6. Edit file on linux using sed utility
7. Remove duplicate successive line using uniq utility
8. Find pattern from a file using grep, egrep or fgrep utility

Chapter 5: List of special characters used in shell script (Advanced)

Sunday, April 5, 2009

A simple shell script to check whether user is root

In many case inside your shell script you need to check whether the user who runs the script is root or not because based on the user you might need to take necessary action inside your shell script.

Following shell script might help you in this case.

Way 01: With system variable $LOGNAME
As echo $LOGNAME show the currently logged in user show we can use this variable to determine whether it is root user.
1)create script
# vi test_root.sh
if [[ $LOGNAME = "root" ]]
then
echo "You are root user"
else
echo "You are $LOGNAME user"
fi

2)Grant execute permission.
# chmod +x test_root.sh

3)Test it by running as root.
# whoami
root

# ./test_root.sh
You are root user

4)Test it by running as oracle user.
# su - oracle

$ whoami
oracle

$ ./test_root.sh
You are oracle user

Way 02: As system variable $UID:
As system variable $UID for root user is zero so we can use that in order to determine whether user is root.
1)create script
# vi test_root2.sh
if [[ $UID = "0" ]]
then
echo "You are root user"
else
echo "You are not root user"
fi

2)Give execute permission.
# chmod +x test_root2.sh

3)Test it by running as root user.
# ./test_root2.sh
You are root user

Way 03: With the command whoami
With the command whoami you can check the user who is logged in. So you can use that in your script.
1)Create script
# vi test_root3.sh
if [ `whoami` = "root" ]
then
echo "You have logged on as root"
else
echo "You are not root user"
fi

2)Grant execute permission.
# chmod +x test_root3.sh

3)Test the script by running it.
# ./test_root3.sh
You have logged on as root