Learn BASH with me in 5 mins

I just started learning Linux bash from today. From my first impression of the language, I infer that it is a language with all the basic capabilities as of an infant high level language. May be I am right or wrong.Time will tell . We will keep going and keep discovering gradually. Let's start with the usual protocol of learning a language.

The HELLO WORLD program.


How to print things in shell. This is the first thing everyone wants to know while learning any language.

Anything that is not a variable is printable . And we print/echo it using the famous ECHO keyword

$ echo hello world
hello world


Printing a number.



$ echo 1
1
Printing a string with double quotes
$ echo "my name is arindam"
my name is arindam
Printing a string with single quotes
$ echo 'my name is Arindam'
my name is Arindam
Printing a number with quotes
$ echo '1' 1

Creating  Variables and recalling them.


So how can we store things. How to recall that stored value. How to change that value.

X=999

Note: There should be no spaces around the assignment operator (=). Also, there is no return value after the assignment statement is executed.

$ X=999

$ echo $X
999

$ $X
bash: 999: command not found

A simple = sign works great for assigning values but, the spaces around a important. Otherwise you will get an error.

To recall the value inside a variable, use the $ sign.
If you don't use the echo keyword and try to print the value by just a $ sign (people coming from languages like python would understand why someone would try such a thing).

Saving Strings in variable



$ X=arin

$ echo $X
arin

$ x="hi world"

$ x=hi world
bash: world: command not found

You can store a single word with spaces around without using quotes. But if there are spaces, then you need to use quotes. Other bash breaks down "x=hi world" as two commands x=hi and world. Obviously this doesn't work.

Dynamically changing value


$ echo $X
99

$ echo $((X+1))
100

What happened here. I wanted to use the variable X and get an incremented value of the same.
You need to use a double parenthesis in these cases. Note that this won't change the value of X to the new value.

Using Bash as a calculator



$ echo $((X*2))+$X
198+99

$ echo $(($((X*2))+$X))
297

This probably is an overkill but , if you need to do it, this is how you can.

From the first line, you can observe that , bash evaluates each section separately, and just displays their value in the same format. This is like interpretation


The second does the job , because we asked to evaluate the equation using $((equation)).
I think this looks messy and risky but, just for example sake, it works.

Another way , is to use the keyword "expr". Whatever is mentioned after this keyword become the expression to be solved/interpreted.

$ echo $(expr 5 + 5)
10

n=4
$ echo $(expr 4 * $n)
16


Iterations and LOOPS


Every body loves loops. Iterations are a part of every language. Bash provides the omnipresent FOR  loop and WHILE loop.


$ for num in 1 2 3
> do
> echo $num
> done
1
2
3

So here, we looped on a list of numbers.


X=1
while [ $X -le 99 ]
do
    echo $X
    X=$((X+2))
done

Here, I have printed from number 1 to 99 but only odd numbers.


Accepting input


Another common feature of any language is accepting an input from the user. We have the 'read' keyword for it.


read name
echo Welcome $name

Ranges

My reference: http://www.cyberciti.biz/faq/bash-for-loop/

How do deal with ranges. Bash has a syntax for that. {start..end}


for num in {1..50}
do
echo $num
done

Now , what if the end limit of your range, is inside a variable. You might think, I'll just do {1..$N}. Sorry that doesn't work. There is a better way to do this. If you know C syntax, then you must be familiar with this.

n=4

$ for ((i=1;i<=n;i++)); do echo $i; done
1
2
3
4


Ranges with Step


We want to add a step value. We can do it as {start..end..step}

$ for num in {1..10..2}; do echo $num; done
1
3
5
7
9

If condition with comparison operators



if [ $A -gt $B ]
    then 
        echo $(($A-$B))
else
    echo $(($B-$A))
fi

There are many operators available. Below table should be referred.


For string comparisons, the operators are different.


Example:


$ if [ 'Y' == 'Y' ]; then echo YES; else echo NO; fi
YES

$ if [ 'N' == 'Y' ]; then echo YES; else echo NO; fi
NO

Multiple conditions inside IF


There might be a condition when you have two or more possibilities for the if or else part to be true.

read D
if [ $D == 'Y' -o $D == 'y' ]; then echo YES; else echo NO; fi

Here, the -o stands for OR. Even || works for OR operation but the syntax changes slightly.

read D
if [ $D == 'Y' ] || [ $D == 'y' ]; then echo YES; else echo NO; fi

Also note, for AND operation , -a is used. Also && can be used.

Problem:

Find out if a triangle is scalene , equilateral or isosceles given sides of a triangle a, b, c.


Sol:


read a
read b
read c

if [ $a -eq $b -a $a -eq $c ];then
 echo EQUILATERAL;
elif [ $a -eq $b ] || [ $a -eq $c ]||[ $b -eq $c ];then 
 echo ISOSCELES;
else 
 echo SCALENE;
fi


Problem:


Find out the average to 3 decimals of accuracy. Given an array of numbers.


Input Format
The first line contains an integer, .
lines follow, each containing a single integer.
Output Format
Display the average of the integers, rounded off to three decimal places.

Soln:



read N
s=0
for ((i=1;i<=N;i++))
do
read temp
s=$((s+$temp))
done
printf "%.3f" $(echo $s/$N | bc -l) 

Total Pageviews