Updated August 10, 2023
Shell programming is fun. But so is Python. People with a background in C, or most importantly, people who use Windows, won’t agree. People often tend to prefer using a based graphical interface to command-line ones. But that is so wrong. The graphical user interface is for people who think the software is doing what its description says. But that is not always the case, especially in the case of shell programming windows, where viruses and malware have created havoc the size of a Tornado. So people using a command-line interface usually agree that what they are doing is right, and I agree with them that they are right.
A simple Graphic User Interface (GUI) based software can cause the entire computer to freeze, resulting in a user getting stuck. Working on a command-line interface is often more elegant, fast, and, importantly, you know what you are executing. But again, using shells and writing programs is not something everyone would prefer to do.
Besides, writing programs in C or Java would be much worse than Graphic user interface-based software in Windows. I am not cursing C or Java here; it is just that they are not suitable for everyday use. And this is where scripting languages like Shell programming and Python languages excel. Today we are at war on which is ideal for smaller and larger applications. Or can we combine them and make something new and better out of them? Let’s look deeper into both of them and see where it takes us.
Bash Shell Scripting
Shell Scripting is fantastic. You can almost do most of your jobs here in just one line of code. For example, say, take this piece of code:
$ touch file.txt | echo -e 'hello\n New\n World\n hello\n Hello' >> file.txt | cat file.txt | sort | Uniq | wc -l
So, as you can see, a lot of shell scripting is happening here, but what exactly is happening? First, the ‘|’ is known as the pipe. It is used to transfer the output of one file to other. The ‘touch’ syntax creates files, and the echo syntax prints any statement. The double right-sided arrows’>>’ are used to insert the output to any file or program. ‘cat’ syntax reads a file’s contents. The command ‘sort’ is utilized to arrange everything in a specific order, and the option ‘uniq’ removes duplicates from the sorted output. ‘wc’ command is used to count lines, and the flag ‘-l’ is used to print the count of lines only. So all of these chained commands do the following.
- First, a file is created with the name file with extension text to inform it’s a text file.
- Users utilize the “echo -e” command to print multiple words inside the “file.txt” file, and they use the escape sequence “\n” or the characters “\n” to create a new line or move to the next line.
- After entering the file’s strings, the program reads and sorts the file in order and then transfers it to the uniq syntax to remove any existing duplicates, which in our case is ‘hello.’
- Finally, we print the number of lines using ‘wc -la to count and publish it on the terminal screen.
So, though the above is just one line of code, it can get complicated when more conditions are inserted. Although shell scripts are valuable, they may not suit every new task. Sometimes, you want things to be simpler, as simple as a Graphic user interface. Shell scripts are perfect for running batch scripts and doing repeated jobs, but at the same time, they do come with some disadvantages:-
- As shell scripts grow larger, they tend to become increasingly complex.
- Scripts re-usage is almost none. Bash scripts are tough to insert in C or other Java codes.
- Advanced features such as HTML parsing are not readily available for Bashash; however, Python is here for the rescue and the most suitable replacement. But is Bash Shell scripting replaceable? Let us take a look.
Python Shell Scripting
Python is installed by default on almost all Linux and UNIX systems. Sometimes the distribution may have an older version, but a simple command can update it. Python Shell programming is easier to understand and cleaner to write, even for beginners. Also, by default, Python has the Read Eval Print Loop style, which helps try out new codes in the interpreter. But just using PPython can be a bit tough without the help of bash shell scripting. Besides, in our previous one-line program, we used the ‘unique’ syntax to remove duplicates, but it did not show us the duplicates. So, let us write a Python program to do the same:-
#!/user/bin/env python import sys#importing system modules to work with directory files if __name__ == "__main__":# Starting with an empty dictionary here. Which is termed as the order#. All keys in this dictionary appear as a name, and the specified values for them# will be the number of times that specific name will appear.order = {}# sys.stdin is an object used for files. All those functions applied to
# a file object can also be used for sys. Stdin.
For order in sys.stdin.readlines():
order = order.strip()
If order in orders:
orders[order] += 1
Else:
orders[order] = 1
for order, count in orders.iteritems():
sys.stdout.write("%d\t%s\n" % (count, order))
This file first reads the input from the sys.stdin object. All the output is written to the sys.stdout object. After creating this script, assuming you have named it order.py, you can execute the following shell script in the terminal, and you will find the total count of all the duplicate strings.
$ cat file.txt | PPython order.py
Similarly, we can also sort this out by using the sort syntax:-
$ cat file.txt | python order.py | sort -rn
Python Shell vs. Bash Shell Programming Scripting
Now we have seen how we can combine Python and shell scripts to create a chain of commands and execute them together. Let’s proceed and see whether Python can replace Bash Shell.
Speaking of bash shell programming, in terms of performance, Bashash the crap out of Python. But if you compare it to data types and other advanced stuff, Bashash lacks compatibility. The start-up time of a bash shell script is 2.8 mili seconds, while that of PPython is 11.1 mili seconds. Bash is a general-purpose language like Python, but both have strengths and weaknesses. Bash shell programming is the default terminal in most Linux distributions; thus, it will always perform faster. But does that mean it can replace Python? Nope. Dealing with large programs becomes complicated in Bash, whereas Python does not. As far as I know, PPython can also be used as an Object-oriented language. If you are just a beginner, you might not even know the difference between the two. Python is an even more elegant scripting language than Ruby and Perl. On the other hand, Bash shell programming is excellent in piping out the output of one command into another.
Shell Scripting is simple, and it’s not as robust as Python. It does not deal with frameworks, and getting going with web-related programs using Shell Scripting is tough. The power of shell scripting lies in the Stream Text editor or sed, the Awk Programs, and similar apps.
File Handling and Web Application Development
Bash Shell Scripting works flawlessly and fast when dealing with files. By handling files, I mean copying, cloning disks, writing backup apps for networking, FTP servers, storing file inputs and accessing them later, and transferring those outputs later on to something else with the help of a pipe. On the other hand, Python is more beneficial for dealing with chunks of data, such as reading data from a file and processing data. If I am more specific, Bashash is not even a programming language. A simple Graphic User Interface (GUI) based software can freeze the entire computer, leaving the user stuck. The primary aim of the shell is to manage system files through the command line to expedite and streamline the process.
Thus, if you know bash shell programming properly, you also know that variables and scopes in Bashash are minimal. On the other hand, Python is more of a shell scripting language than a programming language. If we term Bashash programming language, it’s more like saying Python is an object-oriented shell programming language. You can use an object-oriented way to deal with Python, but it will never be purely object-oriented like C or Java. Similarly, Bashash is a scripting language; It is better to use it as a tool for quickly dealing with files rather than for writing large programs. Also, though Python is a Shell scripting language, it sells within its shell. For example, moving all files which are on the Desktop to some other random directory via Bash shell would go something like this:
$ cd Desktop$ mv * random directory
But on the other hand, doing the same thing in Python is a bit more complicated. It goes something like this: –
import os, globfor fname in glob.glob ('*'):os.rename (name, 'random directory')
However, at best, one can make it the most compact in this manner: –
import os, glob[ os.rename (name, 'random directory') for fname in glob.glob ( '*' ) ]
When learning any language, people often tell you how to get the basics clean and all those stuff, but they won’t tell you how to deal first with the system itself, which is the most important. Developers mainly developed shell scripting languages like Python and Bash to handle the system and its files.
Bash Inside Python?
Yes, you read it right. Until now, we have read about introducing Python scripts inside Shell. But we can also submit Shell Scripts within the scripts of Python. Take this, for example:- Type in ‘apt-get update in the Python shell. You will get some errors like invalid syntax. So, the thing is, if you want to use the bash codes like ‘ls, cd, mv’ or anything else in Python, you will have to import the OS module. Now, do one thing, copy the following code and paste it into the Shell of PPython, and check how it works:-
$ python>>>from os import *>>> system ( 'sudo apt-get update )
And now it works…yay. This is another way how to get Python and bash scripts working together. Additionally, another Python module called Pexpect is specifically designed to work with Bash. Pexpect is a Python module used to spawn child processes, control them, and return results per the child process’s request. The Pexpect module has a straightforward interface to import required modules and child processes inside of it and execute them accordingly. One must install pip on their system to install the ‘expect’ module. The following command can be used to install the module: –
$ pip install expect
The version of Pexpect needs a Python version greater than 3.3 or 2.7.
There is much more to mixing up PPython and Bash. Nothing works as better as a mixture of the script of Python and Bash. This mixture makes the hand fast because of Bash and advanced features because of Python. One can read about Pexpect and its documentation at https://pexpect.readthedocs.org/online.
Recommended Articles
We hope that this EDUCBA information on “Nothing Better Than Mixture of Bash Scripting and Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information,