Data Coding 101 – Intro To Bash – ep5 (with video)

后端存储 Data36

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! :wink:

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

This article below is available in video format as well:

[VIDEO PLACEHOLDER] (coming soon…)

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

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:

  1. food='hamburger
  2. drink='coke'
  3. echo 'I would like to have' $food 'with' $drink Then try to change drink! And use the same echo command:
  4. drink='orange juice'
  5. 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:

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

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 ]

do

echo $i

i=$((i + 1))

done

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 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 less, so it executes the commands again.
  2. It echo s $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 eventually 4 is not less than 4. So while exits.

What you see on your screen is the results of the echo s.

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 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 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.

  1. mcedit
  2. copy-paste your while code (don’t forget the shebang: #!/usr/bin/env bash )
  3. Click “ 10-Quit ” on the botton 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

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!

.

.

.

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

A short explanation:

  • (after the shebang)
  • I have defined 2 bash variables ( $i and $network )
  • then I have defined my while loop
  • which echo s the “Hacking wifi password for…” lines plus the 2 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 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 sleep by yourself!)
  • Then I just simply echo d 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 telling “Hacking…”. Unfortunately you will get caught in the moment, when they will try the password… :wink:

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 echoodd ”.

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

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 $i .

Better, 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 with 3 or 7, instead of the number print “BOOM”.

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

Solution: in the video above! :wink:

Conclusion

If-then-else statements. Check.

Variables. 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!

If you want to get notified about my upcoming articles, videos or webinars, subscribe to myNewsletter!

Cheers,

Tomi Mester

Data36稿源:Data36 (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » Data Coding 101 – Intro To Bash – ep5 (with video)

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录