KludgeCode

is Ben Rudgers

Mini Tutorial: Bashing hello.py

This post is related to Coursera’s Programming for Everyone course.

“Why fire up a text editor when I have a command line?” is the sort of question that I never really asked when I was running Windows as my primary operating system. My default approach was to look for a button to click on. But it’s the sort of question that naturally arises as I spend more time with Linux.

After navigating to the directory where I want to hello.py to live:

[prog4everyone]$ touch hello.py  
[prog4everyone]$ echo print "'hello world'" >> hello.py 
[prog4everyone]$ cat hello.py 
print 'hello world'
[prog4everyone]$ python hello.py  
hello world

touch hello.pytouch creates an empty file named ‘hello.py’ if it does not already exist. Otherwise it changes the timestamp of an existing file.

echo print "'hello world'" >> hello.py has two parts.

  1. The first part is echo print "'hello world'". echo simply repeats what is given as input. In order to pass the double quotation marks " for “hello world” through the echo command, the quotation marks need to be nested in single quotes '. Alternatively, to pass single quotes around ‘hello world’ through echo, they must be must be wrapped in double quotations. In other words echo print '"hello world"' and `echo print “‘hello world'” will both pass good Python syntax.

  2. The second part is >> hello.py. It takes the output of the first part and appends it to the end of the file “hello.py”.

cat hello.py – The cat command concatenates the contents of various files and ouputs the result. In this case the output is sent to the screen, and since only one file is provided as input to cat we just get the contents of that file [i.e. print 'hello world']

python hello.py – This calls the python interpeter with “hello.py” as input. This returns hello world.

Now I know some people are probably upset since using touch to create the hello.py is completely unneccessary because redirection will create a new file if one doesn’t already exist. For example:

[prog4everyone]$ echo print "'goodbye world'" >> goodbye.py
[prog4everyone]$ python goodbye.py
goodbye world
[prog4everyone]$ 

is even more efficient. Please accept an apology. I know that being enamoured with touch to create empty files is unhealthy and compulsive.