Make Your Shell Scripting Easier With Sh Module

Introducing sh

Yesterday, I was surfing the web for a way to use Python for shell scripting, and I bumped into this project called sh. It is a package that allows the passing of parameters and handle outputs. Basically, it’s wrapper around a subprocess that can call out any program as if it were function.


This means having the full functionality of shell scripts, but from within Python. Hurray! FYI, this package only supports OS X, Linux, and FreeBSD. You can use the deprecated version of sh called pbs if you want to use it with Windows.


Where to Begin?

Ok let's start, I’m assuming that you have a Mac or running Linux on a virtual machine. If not, there are tons of tutorials on the web on installing Linux on virtual machines like VirtualBox. Here is a YouTube tutorial that you can check out,


Next, download Python (either 2.7 or 3.2) and have PIP package manager installed. If this isn’t the case, have a look at the official Python documentation.


Let’s Start!!


In the terminal, install the sh package with the following command.1


After you’ve installed sh, run Python on your command line and type this code below.2

On the first line, we are importing the sh package. We need to do this to use the sh package or we won’t able access it. You might be familiar with the touch command on Linux. This creates an empty file, in our case, a file named ‘Hello World!’. Here, we are accessing touch from within the confines of Python. Now, we’re passing to the print statement to show a text output to the console. This will call the Linux ls program, which lists the content of a directory. We’re also passing that a parameter of -l, which prints more detailed information about the contents of the directory we execute this in.


This is what you would similarly see if it worked.


In this next example, we are calling the which command using sh.which. In this case, we pass in the name of the program we want to know the location of.




It should look somewhat like this.


For commands that have dashes in their names, just substitute the dash for an underscore.


(ex. /usr/bin/google-chrome)


This command will open google chrome, and create tabs for and


Multiple Arguments

What if you need to pass multiple arguments to a command? Let’s try it by using the ping command.



In the example above we called ping and specified a count of 3. If we didn’t specify the count, Python will keep running the code until we tell it to stop.


Your terminal should look like this after the command has been prompt.



I only scratched the surface of the uses of the sh package. I think this package is worth looking into and has solved my needs in particular to shell scripting. If you want to learn more about, check out the official documentation here.





 Jaime Gabriel Jingco

Software Engineer/ Applied Labs Assistant Instructor 

Check our Next Webinars


Recent Post