Wednesday, November 16, 2011

Bash Scripting


BASH SCRIPTING AND TOOLS
------------------------
First you need to find out where is your bash interpreter located. Enter the following into your command line:

which bash

Create a file with name hello.sh
vim hello.sh
-----------------------------
#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING
-----------------------------
Every bash shell script starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash.

Navigate to a directory where your hello.sh is located and make the file executable:

$ chmod +rx hello_world.sh 

Now you are ready to execute your first bash script:

./hello.sh 
or
source hello.sh

Simple Backup bash shell script
----------------------------------------------
#!/bin/bash
tar -czf myhome_directory.tar.gz /home/student
--------------------------------------------------

NOw creating backup script with variable
Your backup script and variables:
--------------------------------------------
#!/bin/bash
 OF=myhome_directory_$(date +%Y%m%d).tar.gz
 tar -czf $OF /home/student 
--------------------------------------------

Global vs. Local variables
----------------------------------------------------
#!/bin/bash
#Define bash global variable
#This variable is global and can be used anywhere in this bash script
VAR="global variable"
function bash {
#Define bash local variable
#This variable is local to bash function only
local VAR="local variable"
echo $VAR
}
echo $VAR
bash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR
-------------------------------------------------

To get the value of a variable 
A=10
echo $A
or
echo ${A}

If you want to assign the value of any command output to a variable use:
FILES="$(ls)"
or
FILES=`ls`

If you want to execute any command and assign that value to a variable you can follow this syntax:
<variable>=$(command -option args)

Create a script which will copy all dir with its content to a new dir /dir-backup
-----------------------------------------------
#!/bin/bash
DIR=$(ls -l | grep ^d | cut -d' ' -f10)
mkdir -p /dir-backup
cp -pvrf $DIR /dir-backup
----------------------------------------------

Reading input from user
-----------------------
We can use "read" to take input 
syntax:
read NAME ###--this command will read input from keybord and store the value in NAME variable
If you want to print something before reading input you can use this:
read -p "enter your name" NAME
If you want to take input in hidden manner use this command
read -s -p "enter your name but while entering it will be hidden" NAME 

Syntax of "for loop"
--------------------
for variable in value1 value2 value3 value4
 do 
    command ### loop body
 done
--------------------   

"for loop is very useful to automate:
-------------------------------------
processing multiple files
processing command-line arguments
processing the output of a command
adding multiple users

Q:-How can you zip all *.txt file in your current dir?
vim gip-txt.sh
-------------------------------
for files in $(ls *.txt)
do 
  gzip $files
done 
--------------------------------

Q:-How can you check that a command is successfully executed or not?
A:- By checking Exit Status. Exit status is stored in "$?"
 to chech exit status echo $?
 If the value is 0(zero) means no error.
 A non-zero exit code is usually an error code.
Chech the Exit status 
 ls ; echo $?
 ls c:\windows ; echo $?
See that true returns 0 (success) and false returns 1 (failure).
 true ; echo $?
 false ; echo $?
Anothere very useful command "test". "test" can test so many things :--
* test arguments:
 -d directory
 -e file exists
 -f regular file
 -r readable file
 -w writable
 -x executable
 -s non-empty file
 -n non-empty string
 -z empty string
 -a and
 -o or
 ! not
* STRING comparison:  ==,  !=,  < ,  > , <= , >=
* NUMERIC equality : -eq, -ne, -lt, -gt, -le, -ge
* Square Brackets "[]" insteed of test command you can also use square brackets.

Q:-How can you you check that current user is root or not?
A:- You can check by two way -- you can check username or you can check the uid.
 test "$USER"==root -o $(id -u) -eq 0
 same thing using []
 [ "$USER"==root -o $(id -u) -eq 0 ]

Q:- Test that current user is standard user not a system user.
A:- test $(id -u) -gt 500

Q:- Check that "data" is a file or directory ?
A:- test -d data ; echo $?
 test -f data ; echo $?

Conditional Execution
---------------------
if/else syntax
--------------
if conditional_command 
then 
 list 
else
 list
fi
-------------
if conditional_command
then 
   command 
 elif conditional_command
    then 
    command 
else 
   command 
------------------------------------------

Q:How can we pass data to a shell scrit?
A:There are 2 ways:
1.Through command line (positional parameter)
2.Via standard input(keyboard)

Positional parameters as variable:
$#   : total number of arguments to a shell script
$1   : 1st argument passed
$2   : 2nd argument passed
$0   : name of the executable
"$@" : preserve the word boundaries
EXAMPLE:

#!/bin/bash
echo you exceuted $0 with $# arguments:
for arg in "$@"
do 
 echo $arg
done

This means
Command you executed is : 
[root@localhost ~]# ./name.sh ram rita sita
you exceuted ./name.sh with 3 arguments:
ram
rita
sita

No comments:

Post a Comment