Showing posts with label Bash Scripting. Show all posts
Showing posts with label Bash Scripting. Show all posts

Friday, November 29, 2013

Selection And Repetition Part II

Last time we already learn about selection and repetition using test and operator
right now we will use if,case, for,while, until and select

if

below is the example

#!/bin/bash

key="bash";
read -s -p "Your Password : " pass
if [ $pass==$kunci ]; then
    echo "Success, You are able to login"
else
    echo "Sorry, Your password is wrong";
fi

below is the result

[elvin@TestBed$]./if2
Password anda : bash
Success, You are able to login
[fajar@linux$]./if2
Password anda : Bash
Sorry, Your password is wrong

else will be execute if the condition is not being fulfilled

below is the example of nested if
#!/bin/bash

clear
echo "Menu of the day";
echo "---------------";
echo "1. Noodle    ";
echo "2. Satay     ";
echo "3. Exit      ";
read -p "Your choose [1-3] :" pil;

if [ $pil -eq 1 ]; 
then
   echo "How Many =";
   read sum
   let pay=sum*1500;
elif [ $pil -eq 2 ]; 
then
   echo "How Many =";
   read sum
   let pay=sum*2000;
elif [ $pil -eq 3 ]; 
then
   exit 0
else
   echo "Sorry, Your choose is not available"
   exit 1
fi

echo "Total Payment = Rp. $pay"
echo "THX"

below is the result

[elvin@TestBed$]./if3
Menu of the day
---------------
1. Noodle   
2. Satay 
3. Exit    
Your choose[1-3] :2

How Many = 2

Total Payment = Rp. 4000
THX

case

the function of case is same like if. for sometimes condition, case is more efficience than if command

below is the example

#!/bin/bash

clear
echo -n "Please input your menu :";
read menu;

case $menu in
    noodle | kwetiau | bihun ) echo "$menu is chinese food"
                  break   
                              ;;
    steak | pizza | sandwich ) echo "$menu is western food"
                  break
                  ;;
    *) echo "$menu is not being defined"
                  break
                  ;;
esac

below is the result

[elvin@TestBed$]./cs1
Please input your menu : noodle 
noodle is chinese food

for

for statement is using for repetition

below is the example
#!/bin/bash

for number in 1 2 3 4 5;
do
   echo "number=$number";
done
below is the result

[elvin@TestBed$]./for1
number=1
number=2
number=3
number=4
number=5

while

while statement will do the command as long as the condition is true

below is the example to print odd number

#!/bin/bash

i=1;
while [ $i -le 10 ];
do
  echo "$i,";
  let i=$i+2;
done

below is result

[elvin@TestBed$]./wh1
1,3,5,7,9,

until

until statement will do the command if the condition is false

below is the example

#!/bin/bash

i=1;
until [ $i -gt 10 ];
do
  echo $i;
  let i=$i+1
done

below is the result

[elvin@TestBed$]./ut
1,2,3,4,5,6,7,8,9,10,

select

below is the example

#!/bin/bash
#menu1

clear
select menu
do
  echo "you choose $REPLY is $menu"
done

below is the result
layout:
[elvin@Testbed$]./menu1 Slackware Redhat Mandrake
1) Slackware
2) Redhat
3) Mandrake
 #? 1
you choose 1 is Slackware



Friday, November 22, 2013

Selection And Repetition Part I

In this part, we will learn how to use selection and repetition command which every programming language will used to execute a statement with certain conditional and repeat a few statement with a short code script.

7.1 test dan operator

test is sh shell utility that used to check information about a file and used to compare both string or numeric.
syntax: test expresion
test work proses is return the status information with 0 value (correct) or 1 (false) where this value status can be read by special variable $.
[elvin@TestBed$]test 7 -gt 3
[elvin@TestBed$]echo $?
0
This statement 7 -gt (greather than) 3 is being evaluated test return 0 for variable status $. 
This mean this statement is true.
if we compare with below expresion
[elvin@TestBed$]test 3 -lt 1
[elvin@TestBed$]echo $?
1
 this status value is 1, which mean false statement
if you see the symbol -gt and -lt, this want mean operator.
simple operator is special character that do operation for a few operand, example 2+3.
"+" is an operator. 2 and 3 is an operand. 
for test example, the operator is -lt and -gt, and the number is on left and the operand is on the right. 
Below is the operator that bash can be used:
OperatorInformation
bil1 -eq bil2return true if bil1 is same as bil2
bil1 -ne bil2return true if bil1 is not same as bil2
bil1 -lt bil2return true if bil1 is less than bil2
bil1 -le bil2return true if bil1 is less than enough bil2
bil1 -gt bil2return true if bil1 is greater than bil2
bil1 -ge bil2return true if bil1 is greater than enough bil2

7.1.2. Operasi string

OperatorInformation
-z STRINGreturn true if STRING length is zero
STRING1 == STRING2return true if STRING1 is same as STRING2

7.1.3 Operator file

OperatorInformation
-f FILEreturn true if FILE is exist and is a normal file
-d FILEreturn true is FILE is exist and is a directory

7.1.4 Operator logic

ekspr1 -o ekspr2return true is one of the expression is true  (or,||)
ekspr1 -a ekspr2return true is expression 1 and expression 2 true(and,&&)
! ekspresireturn true if the expression is false (not!)

Simple I/O with bash scripting

I/O is a based of computer work because this capacity make computer so power.
I/O is a device that handle input and output, both for keyboard, floppy, monitor screen, etc. 
beside echo, we can use printf command to print out with output standard, in screen or in file with specific format.

below this example:
#!/bin/bash
#pr1

url="elvin.enderson.blogspot.com";
number=32;

printf "Hi, use printf ala C\n\t\a in bash\n";
printf "My url %s\n %d decimal = %o octal\n" $url $number $number;
printf "%d decimal in float = %.2f\n" $number $number

and below is the result

[elvin@Testbed$]./pr1
Hi, use printf ala C
    in bash
My url  elvin.enderson.blogspot.com
32 decimal = 40 octal
32 decimal in float = 32.00

below it the table for the format control

Format controlinformation
%ddata integer format
%ooctal
%ffloat atau decimal
%xHexadecimal

Input with read

after echo and printf for output process, now we will use command read.
this command very good to read or accept input from standard input

below is the example

#!/bin/bash
#rd1

echo -n "Your name :"
read name;

echo    "Hi $name,  How are you?";
echo    "message and reply :";
read 
echo    "said $name, $REPLY";

below is the result

[elvin@Testbed$]./rd1
Your name : elvin
Hi elvin, How are you?
message and reply :
i'm fine. thanks
said elvin, i'm fine. thanks





Operator Mathematics in bash scripting

When we talking about programming, we can't off with operator mathematics.
In Bash scripting, there are 3 ways to use operator mathematics.

  1. let
  2. expr
  3. substitution
let's us try to combine the 3 ways that we know in one script


#!/bin/bash
#math1

a=10
b=5
#use let
let add=$a+$b
let min=$a-$b
let multiple=$a*$b

#memakai expr
divide=`expr $a / $b`

#use substitution command $((expresion))
mod =$(($a%$b))  #modulus

echo "$a+$b=$add"
echo "$a-$b=$min"
echo "$a*$b=$multiple"
echo "$a/$b=$divide"
echo "$a%$b=$mod"


Below is the result

[elvin@Testbed$]./mat1
10+5=15
10-5=5
10*5=50
10/5=2
10%5=0

for expr function it is also useful for string
example
[elvin@Testbed$]mystr="linux"
[elvin@Testbed$]expr length $mystr
5


Positional Parameter

In previous post, we already learn how to use variable in bash scripting.
In this article, i will share the use in shell scripting.

Positional Parameter

Positional parameter is a variabel that being used by shell to contain argumen that given to shell.
below is the example for the script:

#!/bin/bash
#argumen1

echo $1 is one of popular $2 populer in $3

if we input word beside the script
example

[elvin@Testbed$]./argumen1 bash shell linux
bash is one of popular shell in linux

In this example, we can take conclution that
word bash will be save in positional 1 ($1)
word shell will be save in positional 2 ($2)
word linux will be save in positional 3 ($3)

Below is other example for positional parameter

#!/bin/bash
#argumen2

clear
echo "Your name script   : $0";
echo "How many Argumen   : $#";
echo "The Argumen is     : $*";

and the result

[elvin@Testbed$]./argumen 1 2 3 empat
Your name script  : ./argumen
How many Argumen  : 4
The Argumen is    : 1 2 3 empat




Thursday, November 21, 2013

How to use variable in bash script

Today we will learn more about variable in shell.
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

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


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

(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.

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

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.



Wednesday, November 20, 2013

Hello World

Hi Readers..
Today we will start our first lesson about how to write "Hello world" in our Shell Terminal.

First of all, open your terminal and open your word editor.
in Linux, you can use command vi, nano,vim, pico, or etc.
but in this tutorial. i will using vi as our word editor

let say i give the file name is helloworld.
using command
[elvin@TestBed belajar]$ vi helloworld

After that we press i to insert the text and then we can write below text
#!/bin/bash
echo "Hello World"
And then we can quit using Esc and then hit :wq to save the text

After that we must change the permission first before we able to execute the script
below is the command to change the permission file

[elvin@TestBed belajar]$ chmod 750 helloworld

and then execute the command
[elvin@TestBed belajar$]./helloworld
Hello World

For the tutorial vi editor and permission you can find below
vi editor tutorial
permission access

Tuesday, November 19, 2013

Bash Scripting Introduction

Hi all, Today we gonna learn about bash scripting.
what is bash scripting?
as linux user, we often hear about bash scripting.
script is a set of command that had function to help us. Bash script is a set of command bash. With this bash scripting, we can create a program to help us create an application.
for example, let use see script below.
#!/bin/bash
echo “===================”
echo “Today date is” `date`
echo “Totatl Usage Our computer:”
df -h
then we save this file with name cekusage.sh.
to run this command, there 2 way:
1. ussing command sh.
for example:
sh cekusage.sh
there are some disadvantage using this command that is this command will disable reading from stdin that comes from script and make the script ineffective.
2. using command chmod to change permission in file so we can execute the script .
chmod 555 cekusage.sh (change permission into read and execute for user,group and other).
after that we can use command ./cekusage.sh
SHA-BANG (#!)
===============
what is sha-bang?
sha-bang is header in script that we created. For example #!/bin/bash
In the basic, syntax from sha-bang is
#! path bin that we used
example path: /bin/bash, /bin/sh, /sbin, etc
The use for sha-bang is command interpreter. For analogy, shabang is recognition to script. Shabang had a function to describe which langguage that we use and the command location.
for common use /bin/sh is more popular in UNIX family, In Linux Family is more common using /bin/bash. If we want to use command in UNIX family, we can use sha-bang /bin/sh.