Professional Documents
Culture Documents
Bash Scripting
Bash Scripting
/bin/bash
REDIRECT TO A FILE
echo “hello” > file.txt
>> : APPEND
COMMENTS
: ‘
This is the segment of multi-line comments
Through this script, you will learn How to do multi-line
commenting
‘
CONDITIONAL STATEMENTS
count=10
if (( $count > 9 )) - if [ $count -eq 10 ]
then
echo "the condition is true"
else
echo "the condition is false"
fi
count=10
if (( $count > 9 ))
then
echo "the first condition is true"
elif (( $count <= 9 ))
then
echo "then second condition is true"
else
echo "the condition is false"
fi
& OPERATOR
age=10
if [ "$age" -gt 18 ] && [ "$age" -lt 40 ]
then
echo "age is correct"
else
echo "age is not correct"
fi
age=30
if [[ "$age" -gt 18 && "$age" -lt 40 ]]
then
echo "age is correct"
else
echo "age is not correct"
fi
OR OPERATOR
age=30
if [ "$age" -gt 18 -o "$age" -lt 40 ]
then
echo "age is correct"
else
echo "age is not correct"
fi
age=30
if [[ "$age" -lt 18 || "$age" -gt 40 ]]
then
echo "age is correct"
else
echo "age is not correct"
fi
LOOPS
WHILE
number=1
while [ $number -lt 10 ]
do
echo "$number"
number=$(( number+1 ))
done
number=1
while [ $number -le 10 ]
do
echo "$number"
number=$(( number+1 ))
done
UNTIL
number=1
until [ $number -ge 10 ]
do
echo "$number"
number=$(( number+1 ))
done
FOR LOOP
for i in 1 2 3 4 5
do
echo $i
done
for i in {0..10}
do
echo $i
done
for i in {0..10..2}
#{starting..ending..increment}
do
echo $i
done
do
echo $i
done
SCRIPT INPUT
args=("$@")
echo $@
args=("$@")
echo $@ #prints all the array elements
echo $# #print the array size
Reading file using stdin
while read line
do
echo "$line"
done < "${1:-/dev/stdin}"
Script output
ls -al 1>file1.txt 2>file2.txt
Concatenation
echo "enter Ist string"
read st1
echo "enter 2nd string"
read st2
c=$st1$st2
echo $c
n1=4
n2=20
echo $(( n1 + n2 ))
n1=20
n2=4
echo $(( n1 + n2 ))
echo $(( n1 - n2 ))
echo $(( n1 * n2 ))
echo $(( n1 / n2 ))
echo $(( n1 % n2 ))
FUNCTIONS
function funcName()
{
echo "this is new function"
}
funcName
function funcPrint()
{
echo $1 $2 $3 $4
}
funcPrint Hi This is Linuxhint