Skip to main content

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) 

Popular posts from this blog

Why should you visit Kashmir sooner?

"If there is paradise on Earth, this is it"
And paradise it was . Early winter is the perfect time to plan for a visit to Kashmir. We will suggest to keep your itinerary  short . And enjoy the best trip of your life. 

   My Visit Month : Mid November 2015

As we were flying close to Srinagar, about 20 minutes before landing , all of a sudden , every passenger in the aircraft was on his toes craning theirs necks over the tiny window to catch a glimpse of the above. A fleet of Snow Giants.


   Visit Meena Bazaar in Dal Lake
  You will find a floating village with houses , shops, and hotels on all kinds of boats.


    A night on a House Boat




Take a Shikara ride.Watch the super clear reflection of the mountain. Spot fishes and water birds.



Take a 2 day stay in Pahalgam. Visit Mini Switzerland first day on a horse ride.


Visit Sonemarg. Enjoy the snow.



On your way to Pahalgam, visit apple orchids . Taste all kind of apples. The golden ones are supposed to be the best.



The dark ominous mou…

Kerala : How to plan for a lifetime's experience

I have been planning this for months and it finally came along in the best time. A full stretch Kerala trip with Kanyakumari as an added bonus. I will not tell you what to do, but HOW to do it. How to plan your dream Kerala Trip. 

Caution: Mine was too comprehensive. Needs high energy and will be quite tiring. 

I chose the monsoon theme..I wanted to be in the middle of the action. This is the only place in India which offers monsoon as a tourism opportunity. I was lucky. I expected super heavy rains. Instead. I ended up right in between the rainy season and summer which was Perfect.

Advantages in travelling in mid AugustRainfall almost over.Waterfalls at their fullest.Greenery all over the state.Backwaters, beach sides and rivers all very clean.Abundant coconuts to enjoy.Hotel rates brought down.Less crowd everywhere.Festive Preparation going on.Shopping becomes pocket friendly.Our route map:






Day 1 Day 2 Day 3 Day 4 Day 5 Day 6

CNTLM in Office

If you are facing a proxy problem , CNTLM is a general option everybody considers. But the working of CNTLM is not always guaranteed. I myself get confused every time I need to use it.

What problem are we actually talking about?

While working in offices and restricted environments where firewalls and other invisible barriers stop your requests from going out, you sometimes need a way to temporarily jump over that barrier to get your job done . Example: You might face them while trying to install using pip in command line, trying to clone a personal git repository. 

What is CNTLM exactly?

I think this is best answered by the creator himself. Refer this. You can download it from here. For configuration, you an refer this. There are many uses of CNTLM but I am trying to solve my own problem here. So I will stick to breaking office barriers for now ;) .

Why do I need to use it :
1) Python package installations using PIP
2) Git operations : Cloning and pushing to server.

Here are a set of steps I …