Using python to modify your shell
I’m not a great fan of shell scripts, and have a hard time performing anything even slightly complex with them. Unfortunately sourcing shell scripts is something that is often hard to avoid. So here is a trick to use python for all the logic required and only using the shell script as a wrapper.
The shell script basically just executes a given python script, passing along all the arguments. One argument is reserved for identifying the type of script (sh or csh) calling the python script. Python outputs shell commands that are then evaluated in the shell by ‘eval’.
For bash:
#!/bin/bash
eval `$MYSCRIPTS/test.py sh $@`
For csh:
#!/bin/csh
eval `$MYSCRIPTS/test.py csh $argv`
The python script can then perform the complex stuff and print shell commands for the relevant shell type.
#!/usr/bin/env python
import sys
# Distinguish between sh and csh
shelltype = sys.argv[1]
# Get the rest of the arguments
arguments = sys.argv[2:]
# Generate some fancy commands for the shell
shellcommands = createfancycommands(shelltype, arguments)
# This is shown to the user
print >> sys.stderr, ‘Use stderr for user info:’
# This is evaluated by the shell
print shellcommands
And, voilĂ , the python script takes care of all you worries. Also the overhead involved in supporting both sh and csh is drastically reduced.