In this article I will show you 3 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 hacking wifi passwords! 😉
Note: If you are new here, I suggest to start 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. You got back 3.1415.
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 (eg. by a script)! Also if you store a number (eg. 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 straight-forward one (it will be much easier in Python for instance), but this is what we have in bash. 🙂
All in all: variables can save you time. Also they will be very useful, when you will use if statements and while loops – but let’s just jump on it!
While Loop in Bash
Loops help you to repeatedly execute your command based on a condition. Thus they are very essential part of not just data analysis, but in general computer science and programming. Most of the times we 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 do 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 ]
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 now, 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 a bit bash specific syntax – we don’t have anything similar in Python eg.
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 have 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:
$ivariable is 1, the loop starts again – first checking if
$iis less than 4. Yes it’s less, so it executes the commands again.
$i. 1 printed on the screen.
- Then add 1 to
$i. It’s 2 now.
- Starts over: 2 is still less than 4.
- Print 2 on the screen.
- Add 1 to
$i. It’s 3 now.
- Starts over: 3 is still less than 4.
- Print 3 on the screen.
- Add 1 to
$i. It is 4 now.
- Starts over: and eventually 4 is 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. That what’s the
> sign refers to.
Put while into a bash script
I can’t really suggest to use 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 have shown 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 “10-Quit” on the botton 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 from “mma2wifi” as well, so it will be much easier to modify it later. And to make this more realistic, try to delay each iteration with 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 2 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 draw your attention about 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 telling “Hacking…”. Unfortunately you will get caught in the moment, when they will try the password… 😉
If statements in Bash
Back to the serious command line thingies. With
if you can perform different actions based on a condition. Here’s an example. You give a number to your script and if that number is divisible by 2, then the scripts
echo to the screen “even”, otherwise
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, if it is 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 gives back the remainder of the division by 2. In this case the result of 2/2 is 1, 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 it’s not, then it will execute the command after the
else (see below)
then –» this is the “marker”, that tells to bash, that in case 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 marker, that tells to bash, that if the statement above was not true (false), then execute the command from here instead.
echo 'odd' –» it prints “odd” to your screen
fi –» end of the if statement
Okay, save your bash script, give the rights with
chmod again like we did it 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
$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 to make your input variables more dynamical.
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 to 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 learnt a lot of cool stuff today as well. And I tell you what. There’s only one article left – with some special command line tools – from my Intro to Bash series to reach 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 get notified about my upcoming articles, videos or webinars, subscribe to my Newsletter!