BASICS OF BASH SCRIPTING
BASICS
OF BASH SCRIPTING
variables
Script file ends/extension with sh. Creating a script file
below
Vim example.sh
#!/bin/bash ##Write she-bang sentence (it informs the
shell what kind of programming lang it contains)
#!/bin/php #!/bin/perl #!/bin/python ### so
on
#Comments –
very imp to write what your program execute for/created for
# for ex This script
is created to do blah blah
# this script
is created by someone@domain.com
#Variables:
these are executed by bash programming lang as of other lang(common concept)
Var=value
(string,no,char etc)
Echo $Var #
$ -used to execute variable or command
#end
Now make the
file excutable
Chmod +x
example.sh
Sh
example.sh ## execute using sh
Ex2:
Take backup
from /etc
#!/bin/bash
#this script is
created to do backup
Backup=</mybackup/etc-$(data
+%Y-%m-%d).tgz or destination to store backup>
#date – an
environmental variable
#-$(data
+%Y-%m-%d) – for specifying time stamp
Tar –cvf
$backup /etc
#tar –cvf
<source or call the variable> <destination>
Mkdir /mybackup
Sh example.sh
Ls /mybackup
CONDITIONS
IF STATEMENT: syntax
if[[( expression ]];
Then
Echo something
Or execute code
Else
Echo something
Or execute code
fi #closing of if statement.
Ex: vim example1.sh
#!/bin/bash
A=22
B=33
If[[( “$a” != “$b”]]
Then
Echo
“the result is true”
Else
Echo
“the result is false”
Fi
Chmod +x example1.sh
Sh example1.sh
Ex2:
#!/bin/bash
Echo “ please
enter your name : “
Read name
If [[ “$USER” =
“$name” ] ] # $USER – built
in/environmental variable
Then
Echo “ the user
is already created”
Break;
Else
Useradd $name
Fi
Chmod
+example2.sh
Sh example2
LOOPS
Used in
scripting to repeat a code many a times.
Types of loop:
For loop
It let’s you
iterate over a series of words within a string.
Syntax
For variable in
number
Do
Echo something
or excute code
Done
Ex:
For i in 1 2 3
4 5 or for I in {1..10}
Do
Echo “ welcome
$i Times “
Done
2 .While loop
It executes the
code as long as the condition is true and if the condition is false it stops executing.
Syntax
While
[condition];
Do
Echo
something/excute code/commands
Done
Ex:
A=1
While [ $a le 7
];
Do
Echo “welcome $A
times”
A=$(($A+1))
done
3. Until loop
It excutes the
loop as long as condition is false and if it is true it stops executing.
Ex:
A=1
Until [ $a -le
7 ];
Do
Echo “welcome $A
times”
A=$(($A+1))
Done
Returns nothing
Until [ $a -gt
7 ];
Do
Echo “welcome $A
times”
A=$(($A+1))
Done
Comments
Post a Comment