Learn Python Control Flow and Loops to Write and Tune Shell Scripts – Part 2

by dev.nvcong
0 comment

In the previous article of this Python series we shared a brief introduction to Python, its command-line shell, and the IDLE. We also demonstrated how to perform arithmetic calculations, how to store values in variables, and how to print back those values to the screen. Finally, we explained the concepts of methods and properties in the context of Object Oriented Programming through a practical example.

Write Linux Shell Scripts in Python Programming
Write Linux Shell Scripts in Python Programming

In this guide we will discuss control flow (to choose different courses of action depending on information entered by a user, the result of a calculation, or the current value of a variable) and loops (to automate repetitive tasks) and then apply what we have learned so far to write a simple shell script that will display the operating system type, the hostname, the kernel release, version, and the machine hardware name.

This example, although basic, will help us illustrate how we can leverage Python OOP’s capabilities to write shell scripts easier than using regular bash tools.

In other words, we want to go from

# uname -snrvm
Check Hostname of Linux
Check Hostname of Linux

to

Check Linux Hostname Using Python Script
Check Linux Hostname Using Python Script
freestar.config.enabled_slots.push({ placementName: “tecmint_incontent”, slotId: “tecmint_incontent” });

or

Script to Check Linux System Information
Script to Check Linux System Information

Looks pretty, doesn’t it? Let’s roll up our sleeves and make it happen.

Control flow in Python

As we said earlier, control flow allows us to choose different outcomes depending on a given condition. Its most simple implementation in Python is an if / else clause.

The basic syntax is:

if condition:
    # action 1
else:
    # action 2
  1. When condition evaluates to true, the code block below will be executed (represented by # action 1. Otherwise, the code under else will be run.
  2. A condition can be any statement that can evaluate to either true or false. For example:
1 < 3 # true
firstName == "Gabriel" # true for me, false for anyone not named Gabriel
  1. In the first example we compared two values to determine if one is greater than the other.
  2. In the second example we compared firstName (a variable) to determine if, at the current execution point, its value is identical to “Gabriel
  3. The condition and the else statement must be followed by a colon (:)
  4. Indentation is important in Python. Lines with identical indentation are considered to be in the same code block.

Please note that the if / else statement is only one of the many control flow tools available in Python. We reviewed it here since we will use it in our script later. You can learn more about the rest of the tools in the official docs.

Loops in Python

Simply put, a loop is a sequence of instructions or statements that are executed in order as long as a condition is true, or once per item in a list.

The most simple loop in Python is represented by the for loop iterates over the items of a given list or string beginning with the first item and ending with the last.

Basic syntax:

for x in example:
	# do this

Here example can be either a list or a string. If the former, the variable named x represents each item in the list; if the latter, x represents each character in the string:

>>> rockBands = []
>>> rockBands.append("Roxette")
>>> rockBands.append("Guns N' Roses")
>>> rockBands.append("U2")
>>> for x in rockBands:
    	print(x)
or
>>> firstName = "Gabriel"
>>> for x in firstName:
    	print(x)

The output of the above examples is shown in the following image:

Learn Loops in Python
Learn Loops in Python

Python Modules

For obvious reasons, there must be a way to save a sequence of Python instructions and statements in a file that can be invoked when it is needed.

That is precisely what a module is. Particularly, the os module provides an interface to the underlying operating system and allows us to perform many of the operations we usually do in a command-line prompt.

As such, it incorporates several methods and properties that can be called as we explained in the previous article. However, we need to import (or include) it in our environment using the import keyword:

>>> import os

Let’s print the current working directory:

>>> os.getcwd()
Learn Python Modules
Learn Python Modules

Let’s now put all of this together (along with the concepts discussed in the previous article) to write the desired script.

You may also like

Leave a Comment