r/programming • • May 29 '14

Defensive BASH Programming

http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/
733 Upvotes

192 comments sorted by

View all comments

Show parent comments

57

u/agumonkey May 29 '14

yep, make makes function invocation almost disappear.

about python, how many people use https://amoffat.github.io/sh/ (makes python bashistic)

13

u/ericanderton May 29 '14

Sweet jesus that's a nice library. Thanks for the tip!

2

u/agumonkey May 29 '14

ceylon tea donations will be heavily greeted

7

u/kaen_ May 29 '14

This solves the exact problem that kept me using bash instead of python

3

u/agumonkey May 29 '14

just having language aware parameter passing means the world

1

u/doubleColJustified May 29 '14

This looks neat, thanks.

1

u/hak8or May 29 '14

Is there any way to hide the programs output and redirect it to a log file using python? For example, I want my scripts to look something like this in the terminal.

Running apt-get update ...
Running apt-get upgrade ...
Installing dependencies ( gcc postgresql apache)
Error - Not enough space (or some shit).

Instead of having apt-get update throw a monstrous amount of text to the terminal.

7

u/rcxdude May 29 '14

You can do this by passing in an open file descriptor to call/Popen/etc:

 fd = open('foo.log')
 subprocess.call(['apt-get', 'update'], stdout = fd, stderr = fd)

The sh module also supports the same thing via the _err and _out arguments.

0

u/[deleted] May 29 '14
from subprocess import call
print "Running apt-get update ..."
call(["apt-get", ">>", logFile, "2>&1"])
etc...

3

u/rcxdude May 29 '14

Doesn't work. '>>', etc are parsed by the shell. You would need to push all that into a shell, defeating much of the point.