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

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


Check Linux Hostname Using Python Script
Check Linux Hostname Using Python Script


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
    # 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:
>>> firstName = "Gabriel"
>>> for x in firstName:

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.

If you liked this article, then do subscribe to email alerts for Linux tutorials. If you have any questions or doubts? do ask for help in the comments section.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

7 thoughts on “Learn Python Control Flow and Loops to Write and Tune Shell Scripts – Part 2”

  1. Gabriel,

    Don’t get why this script isn’t working, even after correcting for indentation and adding utf-8 it only runs under IDE’s.

    At the console I still get…..

    ./uname.py: line 1: #!/usr/bin/python: No such file or directory

    I only code in 2.7 hence the change or omission of line one. I Chmod it and that is the correct path to python2.7.
    Yet this is the only python file run at the console that complains like this……….?

  2. The web version does not include indentation where required by python syntax. I added the indentation and got past those errors and then got
    the following:

    SyntaxError: Non-ASCII character ‘\xc3’ in file uname.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

    Also it will not run on windows because os.uname not available except on linux.

    I got around these errors by using pythonanywhere.com on the web. It ran and was neat but I would think some one at tecmint could help with
    the indentation problem and also specify it will not work on Windows.

    • @Paul,
      Thanks for bringing this to our attention. I must confess I never thought I had to state explicitly this would work on Linux only, but we will add that notice as per your suggestion.
      Please add a small note to clarify. As for the indentation, perhaps we will need a different WP plugin. Any ideas?

    • @big joe,
      It’s possible that the web formatting has damaged the indentation a little. But I can assure you that the program works, as you can see in the screenshots.

  3. I prefer to use subprocess.Popen to execute Linux commands:
    uptime = subprocess.Popen([‘uptime’, ‘-s’], stdout=subprocess.PIPE).communicate()[0]

    I would also recommend O’Reilly’s “Python for Unix and Linux System Administration”, by Noah Gift & Jeremy Jones. You can easily find .pdfs (if you don’t want to buy it).

    • @Andy,
      While that is true, on a personal note I prefer to keep things as simple as possible. If there is a Python-native way of executing a given command without spawning new process, I’d usually stick with it. Thank you for the book recommendation, I’ll take a look at it.


Got something to say? Join the discussion.

Have a question or suggestion? Please leave a comment to start the discussion. Please keep in mind that all comments are moderated and your email address will NOT be published.