Friday, 28 September 2012

Linux Shell Script

Introduction

1. You can use any editor text to write shell script.
    # vi script.sh

2. Write your shell script & save it.
    press ESC, then  :wq!.
    press ENTER.

3. Set execute permission to the script.
    # chmod +x [your_script_name]
    or
    # chmod 755 [your_script_name]

4. Then, you can execute your script.
    # ./[your_script_name]
    or
    # bash [your_script_name]
    # sh  [your_script_name]

 *****************************************************************************

How to Write a Shell Script? 

Important

There are 2 types of variable:
  • System Variables (SV)                    - in capital letters
    • Syntax :
      • $variable_name
  • User Defined Variables (UDV)      - in lower letters
    • Syntax :
      • variable_name=value
    • UDV variable name must begin with Alphanumeric character or underscore character (_), followed by >= 1 Alphanumeric character.
    • No space on either side of the equal sign.
    • Variables are case-sensitive.
    • Can define NULL variable.
      • variable_name=
      • variable name=""
 Quotes

"Double Quotes"Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except \ and $).
'Single quotes'Single quotes' - Enclosed in single quotes remains unchanged.
`Back quote
`Back quote` - To execute command

Syntax that holds number of arguments specified on command line.
  • $#  

Syntax that refer to all arguments passed to script.

  • $* or $@
Mathematical Operator in  Shell Script MeaningNormal Arithmetical/ Mathematical StatementsBut in Shell
For test statement with if commandFor [ expr ] statement with if command
-eqis equal to5 == 6if test 5 -eq 6if [ 5 -eq 6 ]
-neis not equal to5 != 6if test 5 -ne 6if [ 5 -ne 6 ]
-ltis less than5 < 6if test 5 -lt 6if [ 5 -lt 6 ]
-leis less than or equal to5 <= 6if test 5 -le 6if [ 5 -le 6 ]
-gtis greater than5 > 6if test 5 -gt 6if [ 5 -gt 6 ]
-geis greater than or equal to5 >= 6if test 5 -ge 6if [ 5 -ge 6 ]

OperatorMeaning
string1 = string2string1 is equal to string2
string1 != string2string1 is NOT equal to string2
string1string1 is NOT NULL or not defined 
-n string1string1 is NOT NULL and does exist
-z string1string1 is NULL and does exist

TestMeaning
-s file   Non empty file
-f file   Is File exist or normal file and not a directory 
-d dir    Is Directory exist and not a file
-w file  Is writeable file
-r file   Is read-only file
-x file   Is file is executable


Operator           Meaning
! expressionLogical NOT
expression1  -a  expression2Logical AND
expression1  -o  expression2Logical OR

Standard FileFile Descriptors numberUseExample
stdin0as Standard input Keyboard
stdout1as Standard output Screen
stderr2as Standard error Screen

2>&1 : is used to redirect both standard output and error to /dev/null
*****************************************************************************

Related Commands


To print or acees UDV.
  • $variable_name
To print contains of variable "abc" type
  • echo $abc
To display text or value of variable
  • echo [options] [string, variables...]
Options
  • -n Do not output the trailing new line.
  • -e Enable interpretation of the following backslash escaped characters in the strings:
  • \a alert (bell)
  • \b backspace
  • \c suppress trailing new line
  • \n new line
  • \r carriage return
  • \t horizontal tab
  • \\ backslash
To perform arithmetic operations.
  • expr op1 math-operator op2
math-operator
  • +
  • -
  • /
  • %
  • \*
To print output of an arithmetic operations.(Both are back quotes)
  • echo `expr op1 math-operator op2`
To determine the exit status of command or shell script.
  • $?
To get input (data from user) from keyboard and store (data) to variable.
  • read variable1, variable2, ..., variableN
 To run 2 commands with 1 command line.
  • command1;command2
To sort contents in a file & redirect the output to new file.
sort [file_name] [new_file_name]

To translate all lower case character to upper case letters.
tr "a-z" "A-Z" [file_name] [new_file_name]

[Remark: All  commands line you can use for Shell Script.]

**************************************************************

if condition
then
 command1 if condition is true or if exit status
 of condition is 0 (zero)
 ...
 ...
fi
 
************************************************************** 

if condition
then
 if condition
 then
  .....
  ..
  do this
 else
  ....
  ..
  do this
 fi
else
 ...
 .....
 do this
fi

************************************************************** 
if condition
then
        condition is zero (true - 0)
        execute all commands up to elif statement
elif condition1 
then
        condition1 is zero (true - 0)
        execute all commands up to elif statement  
elif condition2
then
        condition2 is zero (true - 0)
        execute all commands up to elif statement          
else
        None of the above condtion,condtion1,condtion2 are true (i.e. 
        all of the above nonzero or false)
        execute all commands up to fi
fi

************************************************************** 

for { variable name } in { list }
do
        execute one for each item in the list until the list is
        not finished (And repeat all statement between do and done)
done
 
**************************************************************  

for (( expr1; expr2; expr3 ))
do
        .....
 .....
        repeat all statements between do and 
        done until expr2 is TRUE
Done

 
************************************************************** 
while [ condition ]
do
       command1
       command2
       command3
       ..
       ....
done
 
 
************************************************************** 
case  $variable-name  in
      pattern1)   command
                  ...
                  ..
                  command;;
      pattern2)   command
                  ...
                  ..
                  command;;
      patternN)   command
                  ...
                  ..
                  command;;
      *)          command
                  ...
                  ..
                  command;;
esac
 
 
************************************************************** 
function-name ( )
{
    command1
    command2
    .....
    ...
    commandN
    return
} 
 
************************************************************** 
 
**************************************************************
Example 1:

#!/bin/bash

# ask user the enter a value

echo "Enter an order number: [Enter]"
read orderNumber

#postgresql command line to get the information for the entered order number
command=`psql -d [database_name] -U [user_name] -At << EOF
                   select * from [table_name] where [column_name]='$orderNumber';
                   EOF`
#print of the output
echo $commands
#if string $command is NOT NULL and does exit
if [ -n $command ]
then
#command1 if condition is true or if exit status of condition is 0 (zero)...
.....
#end of if condition
fi
#end the shell script
exit 0


**************************************************************
Example 2:


(a) aScript.sh
#!/bin/bash
#if there is no environment path for $APP_HOME
if [-z $APP_HOME]; then       #if two command line in a line, it need to be seperated by semicolon
     echo "ERROR MESSAGE: ....";
     exit 1;
fi

#remove an existed file
if [-e "[file_name]"]
then
   rm [file_name]
fi

#To remove the trailing slash
APP_HOME=${APP_HOME%/}  ;

(b) mainProgram.sh
#!/bin/bash

# run a script in background

./aScript.sh &

#set date format
NOW=`date + %d-%m-%y`
...
.....

 

No comments:

Post a Comment