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:
- Data Coding 101 – Install Python, R, SQL and bash!
- Data Coding 101 – Intro to Bash ep#1
- Data Coding 101 – Intro to Bash ep#2
- Data Coding 101 – Intro to Bash ep#3
- Data Coding 101 – Intro to Bash ep#4
Variables in Bash
Login to your data server (that we set up before) and type this into the command line:
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:
Oh nice. It returned
Let’s combine this variable with other words and place it into a sentence:
echo "The value of pi is:" $pi
Get it? Variables are great when you want to store different values for further usage. You can also combine them:
echo 'I would like to have' $food 'with' $drinkThen try to change drink! And use the same
echo 'I would like to have' $food 'with' $drink
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:
a=$((a + 1))
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:
while [ $i -lt 4 ]
i=$((i + 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
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
i=$((i + 1)) –» This will modify your
$i variable by adding
1 to it. So your
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
I don’t want to over-explain this, because this is basic logic, but just in case – what’s happening now is:
1, the loop starts again – first checking if
$iis less than
4. Yes, it’s still less, so it executes the commands again.
1printed on the screen.
- Then add
- Starts over:
2is still less than
2on the screen.
- Starts over:
3is still less than
3on the screen.
$i. It is
- Starts over: and finally
4is not less than
4. So while exits.
What you see on your screen is the results of the
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
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.
- copy-paste your
whilecode (don’t forget the shebang:
- Click “Quit” on the bottom right corner and name your script something like
- Give the rights to execute your script from the command line:
chmod 700 while.sh
- Run the script:
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:
Okay, let’s do this!
If you are done with it, check my solution:
- Open up
- 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"
A short explanation:
- (after the shebang)
- I have defined 2 bash variables (
- then I have defined my
echos the “Hacking wifi password for…” lines plus the two variables of mine.
- At the same time I used
sleep 0.2for 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
- 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
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
Let’s try this little
if statement right away!
mcedit and type this script:
#!/usr/bin/env bash i=2 if (( $i % 2 == 0 )) then echo 'even' else echo 'odd' fi
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
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.
If you go back to your script with
mcedit, then you modify
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
$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
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
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).
If-then-else statements. 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!
- If you want to learn more about how to become a data scientist, take my 50-minute video course: How to Become a Data Scientist. (It’s free!)
- Also check out my 6-week online course: The Junior Data Scientist’s First Month video course.
- Or simply subscribe to my Newsletter.