Data Coding 101 – Intro To Bash – ep5

In this article I will show you three data coding concepts that won’t only be useful in bash, but Python and R as well! Today we will go into variables, if-then-else statements and while loops. Oh, and I will also show you how to prank your friends – pretending to hack wifi passwords! 😉

Note: If you are new here, I suggest starting with these previous data coding and/or bash articles:

How to Become a Data Scientist
(free 50-minute video course by Tomi Mester)

Just subscribe to the Data36 Newsletter here (it’s free)!

Variables in Bash

Login to your data server (that we set up before) and type this into the command line:

pi=3.1415

Congrats! You have created your first variable by assigning 3.1415 to the word pi. Why is this useful? First of all, you can refer to this variable anytime. Try this bash command:

echo $pi

data science command line bash variables 1

Oh nice. It returned 3.1415.

Let’s combine this variable with other words and place it into a sentence:
echo "The value of pi is:" $pi

data science command line bash variables 2

Get it? Variables are great when you want to store different values for further usage. You can also combine them:

  1. food='hamburger
  2. drink='coke'
  3. echo 'I would like to have' $food 'with' $drinkdata science command line bash variables 3Then try to change drink! And use the same echo command:
  4. drink='orange juice'
  5. echo 'I would like to have' $food 'with' $drink

data science command line bash variables 4

On the previous step we have just modified the $drink variable. You can do it manually like we just did – simply assigning a new value. Or you can do it automatically (e.g. with a script)! Also if you store a number (e.g. an integer) as a variable, you can do some basic mathematical operations with it. Try this:

  1. a=1
  2. echo $a
  3. a=$((a + 1))
  4. echo $a

data science command line bash variables addition

I know, the syntax is not the most straightforward (it’s done much easier in Python, for instance), but this is what we have in bash. 🙂

All in all: variables can save you time. And they will be very useful when you use if statements and while loops – but let’s just jump in!

While Loop in Bash

Loops help you to repeatedly execute your command based on a condition. Thus they are an essential part not just of data analysis, but general computer science and programming. Most of the time we’ll use for loops or while loops. This time I’ll show you the while loop and in my Python tutorials I’ll get back to the for loop.

The logic of the while loop is very simple. What you are doing is telling bash to repeat one or more specific commands until a condition is fulfilled. I am going to give you the easiest example. Type this into the command line:

i=0
while [ $i -lt 4 ]
do
echo $i
i=$((i + 1))
done

data science command line bash while loop 1

Here’s what happened line by line:

i=0 –» you defined a variable

while [ $i -lt 4 ] –» while is the command that will let bash know that you are doing a loop here. And [ $i -lt 4 ] is the condition: your loop will be running until $i is less than 4.

do –» This tells to the command line that here starts the command that you want to execute repeatedly. Note that this is pretty bash-specific syntax – we don’t have anything similar in Python, for instance.

echo $i –» This is the first command that I want to execute inside the loop. It prints the $i variable to your screen. Remember? You defined it to be 0, so it prints 0.

i=$((i + 1)) –» This will modify your $i variable by adding 1 to it. So your $i is 1 now. This is a key element of your while loop, because $i was the parameter that you used in your condition. So increasing this number with every iteration will control and stop your loop, once it has run enough.

done –» The end of your loop. This will send you back to the line of while.

I don’t want to over-explain this, because this is basic logic, but just in case – what’s happening now is:

  1. $i variable is 1, the loop starts again – first checking if $i is less than 4. Yes, it’s still less, so it executes the commands again.
  2. It echos $i. 1 printed on the screen.
  3. Then add 1 to $i. It’s 2 now.
  4. Starts over: 2 is still less than 4.
  5. Print 2 on the screen.
  6. Add 1 to $i. It’s 3 now.
  7. Starts over: 3 is still less than 4.
  8. Print 3 on the screen.
  9. Add 1 to $i. It is 4 now.
  10. Starts over: and finally 4 is not less than 4. So while exits.

What you see on your screen is the results of the echos.
If you still don’t get the concept 100%, here’s a small exercise: what happens if you change the order of the i=$((i + 1)) and the echo $i commands? First try to guess the result, then execute the command.

Note: A new prompt just showed up (>). When you type while, bash knows by default that you want to execute a multi-line command. So it opens you a new line, but manages your command as one coherent command. That what’s the > sign refers to.

Put while into a bash script

I can’t really recommend using multiline bash commands (like while or if) directly from the command line. It’s hard to modify them when you misspell them or anything. So trust me, at this point it’s better to open up a text-editor and put them into a script.
In this previous article I showed you how to create a shell script. We will do the exact same here. Open up mcedit and copy-paste your while function in it. Then save and add the correct rights to run your script.

  1. mcedit
  2. copy-paste your while code (don’t forget the shebang: #!/usr/bin/env bash)data science command line bash while loop in a script
  3. Click “Quit” on the bottom right corner and name your script something like while.sh.
  4. Give the rights to execute your script from the command line:
    chmod 700 while.sh
  5. Run the script:
    ./while.sh

data science command line bash while loop running

Test yourself #1 – aka. Hacking wifi password…

Okay, don’t get too excited here, you won’t hack wifi passwords for real, but you can prank your friends a bit at least.
Here’s your exercise, based on the above, create a command.

Create a bash script that prints on your screen:

Hacking wifi password for mma2wifi: 1%
Hacking wifi password for mma2wifi: 2%
Hacking wifi password for mma2wifi: 3% 
. 
. 
. 
Hacking wifi password for mma2wifi: 100% 
processing 
processing 
Password is: Lx612!w?sq22LE

Let’s make a variable for mma2wifi as well, so it will be much easier to modify it later. And to make this more realistic, try to delay each iteration by 0.2 second, so you won’t print everything at once on your screen, but more like this:

data science command line bash exercise while loop

Okay, let’s do this!
.
.
.
Ready?
If you are done with it, check my solution:

  1. Open up mcedit
  2. Use this script:
#!/usr/bin/env bash

network='mma2wifi'
i=0

while [ $i -lt 100 ]
do
i=$((i + 1))
echo "Hacking wifi password for" $network $i"%"
sleep 0.2
done

echo processing
sleep 1
echo processing
sleep 1

echo "Password is: Lx612!w?sq22LE"

data science command line bash excersize while loop 2

A short explanation:

  • (after the shebang)
  • I have defined 2 bash variables ($i and $network)
  • then I have defined my while loop
  • which echos the “Hacking wifi password for…” lines plus the two variables of mine.
  • At the same time I used sleep 0.2 for the delays. (Note: I haven’t written about this command before, but in my previous article I drew your attention to the importance of googling when you don’t know something… so I hope you googled something like “bash delay command” and found sleep by yourself!)
  • Then I just simply echod the rest to the screen.

3. Again, to execute your script, give access for yourself to run it: chmod 700 [yourscriptname.sh] and run the script with ./[yourscriptname.sh]

Note: This is a very simple script, but I pranked my friends so many times with it, when they asked “Do you know the wifi password?” and I answered “No, man, but I can find it out for you.” It’s priceless to see their face, when they see the black screen saying “Hacking…”. Unfortunately you will get caught when they try the password… 😉

If statements in Bash

Back to the serious command line functions. With if you can perform different actions based on a condition. Here’s an example. You feed a number to your script and if that number is divisible by 2, then the script echos to the screen even, otherwise it echos odd.

Let’s try this little if statement right away!
Open mcedit and type this script:

#!/usr/bin/env bash

i=2

if (( $i % 2 == 0 ))
then
echo 'even'
else
echo 'odd'
fi

data science command line bash if 1

Note: I used the Tab key in my script to make it more readable. But it doesn’t affect the functionality at all.

Line by line:
#!/usr/bin/env bash –» Shebang. Never forget it.

i=2 –» This is your variable, that you will check to see if it’s odd or even.

if (( $i % 2 == 0 )) –» Just like it was in while, this line tells bash that you want to execute an if command. And after that, you define your condition. This is a tricky one. $i % 2 returns the remainder of the division by 2. In this case the result of 2/2 is 1, and the remainder is 0. Then the last part checks if this remainder equals to zero or not. If it equals, then it will execute the command after the then (see below); if not, then it will execute the command after the else (see below).

then –» this is the “flag” that tells bash that if the statement above was true, then execute the commands from here.
echo 'even' –» it prints “even” to your screen
else –» and this is the other “flag” that tells bash that if the statement above was not true (false), then execute the command here instead.
echo 'odd' –» it prints “odd” to your screen
fi –» end of the if statement

Okay, save your bash script, give permission with chmod again like we did before – and run your script. You should get back even on your Terminal.

data science command line bash if test

If you go back to your script with mcedit, then you modify $i to 3 and run the script again, you will get odd of course.

This is how if works… Not too complicated, right?

If statement with dynamic input variable

Well, it’s not the most practical thing to check the parity of a number that’s hard-coded into the script. Here’s a little tweak that will help you make your input variables more dynamic.

Modify your original script! When you define the $i parameter, instead of 2, add $1. Your script will look like this:

#!/usr/bin/env bash

i=$1
if (( $i % 2 == 0 ))
then
echo 'even'
else
echo 'odd'
fi

This is a special syntax for bash scripting. $1 tells bash that it can accept extra parameters from the command line when you execute your script. When you run your script, simply add a number after the name of your script. It will be automatically fetched into $1 and then into $i.

data science command line bash if dinamyc parameter

Just check out the screenshot above. Whatever number you add after your script, it will be automatically added to the variable called $1 — that you can refer to in your script.

Why $1? Because it’s the first parameter you add after the name of your script. But you could add more. E.g.:

./my_random_script.sh 100 450

In this example, the name of the script is my_random_script.sh, the first dynamic input variable is 100 (I can refer to it as $1 in the script) and my second dynamic input variable is 450 (I can refer to it as $2 in the script).

Pretty cool, huh?

Test yourself #2

Here’s the ultimate test for this article!

Print numbers on your screen from 1 to 100. But for every number that’s divisible by 3 or 7, instead of the number, print “BOOM.”

Hint: you will need both if and while to solve this…

Solution (put this into a script):

#!/usr/bin/env bash

i=1
while [ $i -le 100 ]
do

if (( i % 3 == 0 || i % 7 == 0 ))
    then
	echo 'BOOM'
    else
	echo $i
fi

i=$((i + 1))
done

The only new thing here is the condition in the if statement:
(( i % 3 == 0 || i % 7 == 0 ))
Translate this from Bash to English: divisible by 3 (i % 3 == 0) or (||) divisible by 7 (i % 7 == 0).

Conclusion

If-then-else statements. Check.

Variables. Check.

While loops. Check.

You have learned a lot of cool stuff today as well. And I’ll tell you what. There’s only one article left – with some special command line tools – from my Intro to Bash series, which will get you to a level where you can start your own bash pet project and learn more and more by doing, and less and less by reading articles! Wanna continue? This way please!

Cheers,
Tomi Mester

Cheers,
Tomi Mester

The Junior Data Scientist's First Month
A 100% practical online course. A 6-week simulation of being a junior data scientist at a true-to-life startup.