[1] Linux Shell Coding
[1] Linux Shell Coding
➔ cd : change directory
➔ ls: Show list of all files in that directory
➔ mkdir: make folder
➔ rm -R <dir>: delete all files in directory
➔ touch: create a file
➔ chmod <permission> <filename>: Add permissions
Permission
■ r:read
■ w: write
■ x: execute
■ X: execute only if the file is a directory or
already has execute permission for some users.
■ t: restricted deletion flag or sticky bit
■ s: Set user / group id on execution
command: ./hello.sh
2)Variables:
$CAPITAL_CASE_VARIABLE_NAME = System Variable
$lower_case_variable_name = User Variable
Into_variable.sh
#! /bin/bash
a=10
b=20
echo a = $a and b = $b
3)Arithmetic Operation:
#! /bin/bash
a=10
b=20
echo $((a+b))
#! /bin/bash
a=10
b=20
c=$((a+b))
echo $c
Precision of number:
#! /bin/bash
echo "scale=5;11.211/3" | bc
Power:
#! /bin/bash
echo "2^8" | bc -l
#-l is used to invoke math library
Square root:
#! /bin/bash
echo "scale=4;sqrt(13)" | bc -l
#! /bin/bash
echo "Enter a & b:"
read a b
echo a = $a and b= $b
#! /bin/bash
read -p "Enter a:" a
read -p "Enter b:" b
echo a = $a and b= $b
#! /bin/bash
read -p "Enter id:" id
read -sp "Enter password:" pass
echo id = $id and pass= $pass
#! /bin/bash
args=("$@")
echo $@
echo $#
#! /bin/bash
args=("$@")
echo ${args[0]} ${args[1]} ${args[2]}
if [ condition ]
then
#code to be executed if the condition is satisfied
else
#code to be executed if the condition is not satisfied
fi
fi
Condition:
● -eq : equals to
example: if [ $var -eq 0 ]
● -ne : not equals to
example: if [ $var -q ne 0 ]
● -gt Or > : Greater than
example: if [ $var -gt 0 ]
if [ $var > 0 ]
● -lt Or < : Less than
example: if [ $var -gt 0 ]
if [ $var > 0 ]
● -ge Or >= : Greater than equals to
example: if [ $var -ge 10 ]
if [ $var >= 10 ]
● -le Or <= : Greater than equals to
example: if [ $var -le 10 ]
if [ $var <= 10 ]
#! /bin/bash
a=10
if [ $a -eq 10 ]
then
echo $a is equal to 10
else
echo $a is not equal to 10
fi
#! /bin/bash
a=13
if [ $a -ge 10 ]
then
echo $a is greater than or equal to 10
fi
#! /bin/bash
pass=abc123
read -sp "Enter your password:" inp
echo
if [ $pass == $inp ]
then
echo welcome
else
echo incorrect password
fi
7) Loop Statement:
● While:
Syntax:
while [ condition ]
do
#code to be executed as long as the condition is satisfied
done
#! /bin/bash
i=1
while [ $i -lt 10 ]
do
echo $i
((i++))
done
#! /bin/bash
i=1
while (($i <= 10 )) #we can use relational sign inside (( ))
do
echo $i
((i++))
done
● For :
Syntax:
for variable in {range_start..range_end}
#code to be executed as long as the condition is satisfied
done
#! /bin/bash
for i in {1..10}
do
echo $i
done
#! /bin/bash
for ((i=1;i<=10;i++))
do
echo $i
done
8) Array
a) Indirect Declaration
ARRAYNAME[INDEXNR]=value
b) Explicit Declaration
declare -a ARRAYNAME
c) Compound Assignment
Or
#! /bin/bash
echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX}