Database Reference
In-Depth Information
Example 2-3. Python script that computes the factorial of an integer (~/book/ch02/
fac.py)
#!/usr/bin/env python
def factorial ( x ):
result = 1
for i in xrange ( 2 , x + 1 ):
result *= i
return result
if __name__ == "__main__" :
import sys
x = int ( sys . argv [ 1 ])
print factorial ( x )
This script computes the factorial of the integer that we pass as a command-line
argument. It can be invoked from the command line as follows:
$ book/ch02/fac.py 5
120
In Chapter 4 , we'll discuss in great detail how to create reusable command-line
tools using interpreted scripts.
Shell function
A shell function is a function that is executed by the shell itself; in our case, it is
executed by Bash. They provide similar functionality to a Bash script, but they
are usually (though not necessarily) smaller than scripts. They also tend to be
more personal. The following command defines a function called fac , which—
just like the interpreted Python script we just looked at—computes the factorial
of the integer we pass as a parameter. It does this by generating a list of numbers
using seq , putting those numbers on one line with * as the delimiter using paste
(Ihnat & MacKenzie, 2012), and passing this equation into bc (Nelson, 2006),
which evaluates it and outputs the result:
$ fac () { ( echo 1; seq $1 ) | paste -s -d \* | bc; }
$ fac 5
120
The file ~/.bashrc , which is a configuration file for Bash, is a good place to define
your shell functions so that they are always available.
Alias
Aliases are like macros. If you often find yourself executing a certain command
with the same parameters (or a part of it), you can define an alias for this. Aliases
are also very useful when you continue to misspell a certain command (see his
GitHub profile for a long list of useful aliases). The following commands define
two aliases:
Search WWH ::




Custom Search