Bash Scripting Notes
Bash Scripting Notes
Variables
to declare a variable
o <variable name>=<variable value>
o make sure there is no space before and after = sign
o num=100
o num = 100 is considered as an error
to get value of a variable
o $<var name>
o echo num => num
o echo $num => 100
to get value from user and store in a var, use read function
o read <var1> <var2>…
o read –p “enter number: ” num
o echo –n “enter number: “
o read num
to get command line arguments
o the 0th argument is always the file/program name: $0
o the first argument is 1 and to get the value of 1st argument use : $1
o the second argument is 2 and to get the value of 2nd argument use : $2
to get count of command line arguments: $#
to get all command line arguments: $@
Operations:
to perform an operation / evaluate an expression
o use expr keyword
o Syntax:
expr <expression>
expr $n1 + $n2
to get the answer/return value of expression
value=$(expr $n1 + $n2)
to use mathematical operators
o add: (+)
o multiplication: (\*)
o modulo: (%)
o subtract: (-)
o division: (/)
o exponent: (**)
Control Structures
if condition
o syntax:
if [ <condition> ]; then
<body>
fi
o syntax:
if [ <condition> ]
then
<body>
fi
if..else block
o syntax:
if [ <condition> ]; then
<if block>
else
<else block>
fi
if..elif..else block
o syntax:
if [ <condition> ]; then
<if block>
elif [ <condition> ]; then
<else if block>
else
<else block>
fi
Loops
for loop
o syntax:
for <temp var> in <array>
do
<block>
done
o syntax 2:
for <temp var> in <array>; do
<block>
done
o syntax 3:
for <temp var> in $(seq <lower bound> <upper bound> ); do
<block>
done
while loop
o syntax:
while [ <condition> ]
do
<code>
done
o syntax:
while [ <condition> ]; do
<code>
done
function