Published on

shell quickstart

basis

define variables

#!/bin/bash
greeting=Hello
name=John
echo $greeting $name

Arithmetic Expressions

OPERATORUSAGE
+addition
-subtraction
*multiplication
/division
**exponentiation
%modulus

numberical expressions

# built-in
var=$((expression))
# use bc
echo "scale=2;22/7" | bc

read user input

#!/bin/bash

# read variable_name
# read -p "Enter your age" variable_name

echo "Enter a numner"
read a

echo "Enter a numner"
read b

var=$((a+b))
echo $var

Numeric Comparison logical operators

OPERATIONSYNTAXEXPLANATION
Equalitynum1 -eq num2is num1 equal to num2
Greater than equal tonum1 -ge num2is num1 greater than equal to num2
Greater thannum1 -gt num2is num1 greater than num2
Less than equal tonum1 -le num2is num1 less than equal to num2
Less thannum1 -lt num2is num1 less than num2
Not Equal tonum1 -ne num2is num1 not equal to num2

Conditional Statements (Decision Making)

  • if...then...fi statements
  • if...then...else...fi statements
  • if..elif..else..fi
  • if..then..else..if..then..fi..fi.. (Nested Conditionals)

loop with numbers

#!/bin/bash

for i in {1..5}
do
    echo $i
done

loop with strings

#!/bin/bash

for s in cyan magenta yellow
do
	echo $s
done

while loop

#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
   echo "$i"
  (( i += 1 ))
done

reading file

#!/bin/bash

LINE=1

while read -r CURRENT_LINE
	do
		echo "$LINE: $CURRENT_LINE"
    ((LINE++))
done < "sample_file.txt"

execute commands with back ticks

#!/bin/bash

var=`df -h | grep tmpfs`
echo $var

get arguments for scripts from the command line

#!/bin/bash

for x in $@
do
    echo "Entered arg is $x"
done